如何使用金字塔在计算机的绝对路径上托管静态文件?

问题描述

我从快速教程页面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)时,应用程序将显示绝对路径{{1} }在服务器上,如上面的文件/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

但是,这不起作用。如何获得使用金字塔的资产的绝对路径

解决方法

如果希望将

class Board include WinCondition COORDINATES = { 1 => [0,0],2 => [0,1],3 => [0,2],4 => [1,5 => [1,6 => [1,7 => [2,8 => [2,9 => [2,2] } 作为HTML的filepath标签中的src属性放置,则需要将其作为URL。浏览器需要请求资产。您应该在该图像标签中执行类似imgrequest.static_url(...)的操作。这是问题的URL生成部分。

当客户端/浏览器请求该URL时,第二部分实际上是在提供文件内容。您可以使用静态视图来支持将磁盘上的文件夹映射到应用程序中的URL结构,方法与request.route_url(...)相同。金字塔文档https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/assets.html中有一章对此进行了介绍。还有一节专门介绍如何在磁盘上使用绝对路径。如果您认为有必要,可以在应用程序中注册多个静态视图。