Python Pyramid 静态资源
通常需要在模板响应中包含一些资源,即使存在某些动态数据,这些资源也保持不变。这些资源被称为静态资产。媒体文件(.png,.jpg等),用于执行一些前端代码的JavaScript文件,或用于格式化HTML的样式表(.css文件)都是静态文件的示例。
Pyramid将这些静态资产从服务器文件系统中的指定目录传送给客户端浏览器。Configurator对象的 add_static_view() 方法定义了路由名称和包含静态文件(如图像、JavaScript和CSS文件)的文件夹的路径。
按约定,使用’static’目录存储静态资产,并使用add_static_view()方法如下所示:
config.add_static_view(name='static', path='static')
定义了静态路由后,使用HTML脚本时可以通过 request.static_url() 方法获取静态资源的路径。
静态图片
在下面的示例中,Pyramid标志将在logo.html模板中渲染。因此,”pyramid.png”文件首先放置在静态文件夹中。现在可以将其作为HTML代码中标签的src属性使用。
<html> <body> <h1>Hello, {{ name }}. Welcome to Pyramid</h1> <img src="{{request.static_url('app:static/pyramid.png')}}"> </body> </html>
示例
应用程序代码通过 add_static_view() 更新配置器,并定义 index() 视图来渲染上述模板。
from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config(route_name='index', renderer='templates/logo.html') def index(request): return {'name':request.matchdict['name']} if __name__ == '__main__': with Configurator() as config: config.include('pyramid_jinja2') config.add_jinja2_renderer(".html") config.add_route('index', '/{name}') config.add_static_view(name='static', path='app:static') config.scan() app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) server.serve_forever()
输出
运行以上代码启动服务器。在浏览器中使用 http://localhost:6543/Guest 作为URL。这里的’Guest’是由视图函数中的 matchdict 对象捕获的路径参数,并作为上下文传递给logo.html模板。浏览器现在显示Pyramid标志。
JavaScript作为静态资产
这是另一个静态文件的例子。一个JavaScript代码 hello.js 包含一个名为 myfunction() 的定义,在以下HTML脚本(templates\hello.html)中的 onload 事件中执行。
<html> <head> <script src="{{request.static_url('app:static/hello.js')}}"></script> </head> <body onload="myFunction()"> <div id="time" style="text-align:right; width="100%"></div> <h1><div id="ttl">{{ name }}</div></h1> </body> </html>
示例
保存在static文件夹中的 hello.js 代码如下:
function myFunction() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); var msg=""; if (h<12) { msg="Good Morning, "; } if (h>=12 && h<18) { msg="Good Afternoon, "; } if (h>=18) { msg="Good Evening, "; } var x=document.getElementById('ttl').innerHTML; document.getElementById('ttl').innerHTML = msg+x; document.getElementById('time').innerHTML = h + ":" + m + ":" + s; }
输出
该函数检测当前时间的值,并根据一天中的时间(早晨、下午或晚上)为变量 msg 分配适当的值。
将 hello.js 保存在 static 文件夹中,将hello.html保存在 templates 文件夹中,并重新启动服务器。浏览器应该显示当前时间和相应的消息。