【问题标题】:How to use Pyramid to host static files at an absolute path on my computer?如何使用 Pyramid 在我的计算机上以绝对路径托管静态文件?
【发布时间】:2020-12-11 23:46:38
【问题描述】:

我从快速教程页面here 创建了一个简单的 Pyramid 应用程序,其中包含与问题相关的以下文件:

  1. tutorial/__init__.py:
from pyramid.config import Configurator


def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.add_route('home', '/')
    config.add_route('hello', '/howdy')
    config.add_static_view(name='static', path='tutorial:static')
    config.scan('.views')
    return config.make_wsgi_app()
  1. tutorial/views/views.py:
from pyramid.view import (
    view_config,
    view_defaults
    )


@view_defaults(renderer='../templates/home.pt')
class TutorialViews:
    def __init__(self, request):
        self.request = request

    @view_config(route_name='home')
    def home(self):
        return {'name': 'Home View'}

    @view_config(route_name='hello')
    def hello(self):
        return {'name': 'Hello View'}
  1. tutorial/templates/image.pt:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Quick Tutorial: ${name}</title>
    <link rel="stylesheet"
          href="${request.static_url('tutorial:static/app.css') }"/>
</head>
<body>
<h1>Hi ${name}</h1>
<img src="${filepath}">
</body>
</html>

我想向我的应用程序添加一个 URL 路由,这样当用户转到 www.foobar.com/{filename}(例如:www.foobar.com/test.jpeg)时,应用程序将显示来自服务器上绝对路径 /Users/s/Downloads/${filename} 的图像,如在上面的文件tutorial/templates/image.pt 中显示。

这是我尝试过的:

  • 在文件tutorial/__init__.py中,添加config.add_route('image', '/foo/{filename}')
  • 在文件development.ini中,添加了设置image_dir = /Users/s/Downloads
  • 在文件tutorial/views/views.py中添加如下视图image
@view_config(route_name='image', renderer='../templates/image.pt')
def image(request):
    import os
    filename = request.matchdict.get('filename')
    filepath = os.path.join(request.registry.settings['image_dir'], filename)
    return {'name': 'Hello View', 'filepath': filepath}

但是这不起作用。如何获取使用 Pyramid 的资产的绝对路径?

【问题讨论】:

  • 我想我在你的另一个问题中回答了这个问题stackoverflow.com/a/63542264/2214933
  • @StevePiercy 的问题是我有两个存储图像的文件夹,这就是我尝试使用 URL 模式匹配的原因。添加两个静态视图不起作用?如何使用绝对路径并使用两个目录进行图像托管?
  • 我认为您并没有真正阅读我的回答,我说:“配置多个静态路由也可以,如果您想要的话。”

标签: pyramid


【解决方案1】:

filepath 如果您希望将其作为src 属性放在 HTML 中的 img 标记中,则必须是 url。浏览器需要请求资产。您应该在该图像标签中执行request.static_url(...)request.route_url(...) 之类的操作。这是问题的 URL 生成部分。

第二部分实际上是在客户端/浏览器请求该 URL 时提供文件内容。您可以使用静态视图来支持将磁盘上的文件夹映射到应用程序中的 URL 结构,就像 add_static_view 所做的那样。 Pyramid 文档中有一个关于此的章节https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/assets.html。还有一节专门介绍在磁盘上使用绝对路径。如果您认为有必要,您可以在您的应用中注册多个静态视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-25
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多