使用Werkzeug和Jinja2的上下文处理器 [英] Context processor using Werkzeug and Jinja2

查看:140
本文介绍了使用Werkzeug和Jinja2的上下文处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用正在App Engine上运行,并使用 Werkzeug Jinja2 。我想要有一些功能上与Django自己的上下文处理器相当的东西:一个可以请求并且向模板上下文添加东西的可调用函数。我已经有一个上下文处理器,为模板上下文添加了一些东西,但是如何让这个请求部分工作?我实现了上下文处理器作为一个只能返回一个字典的后缀用于更新上下文的调用。

My application is running on App Engine and is implemented using Werkzeug and Jinja2. I'd like to have something functionally equivalent of Django's own context processor: a callable that takes a request and adds something to the template context. I already have a "context processors" that add something to the template context, but how do I get this request part working? I implemented context processors as a callables that just return a dictionary that later is used to update context.

例如,我想添加一些包含在 request.environ

For example, I'd like to add something that is contained in request.environ.

推荐答案

全局模板中使用线程本地代理在Werkzeug。

One way of achieving this is through late-bound template globals using the thread-local proxy in Werkzeug.

一个简单的例子请求进入模板全局变量:

A simple example that puts the request into the the template globals:

from werkzeug import Local, LocalManager
local = Local()
local_manager = LocalManager([local])

from jinja2 import Environment, FileSystemLoader

# Create a global dict using the local's proxy to the request attribute
global_dict = {'request': local('request')}
jinja2_env = Environment(loader=FileSystemLoader('/'))
jinja2_env.globals.update(global_dict)

def application(environ, start_response):
    """A WSGI Application"""
    # later, bind the actual attribute to the local object
    local.request = request = Request(environ)

    # continue to view handling code
    # ...

application = local_manager.make_middleware(application)

现在在你的任何模板中,当前请求将显示绑定到变量request。当然这可能是环境中的其他事情。诀窍是使用本地代理,然后在渲染任何模板之前设置该值。

Now in any of your templates, the current request will appear bound to the variable "request". Of course that could be anything else in environ. The trick is to use the local proxy, then set the value before you render any template.

我也应该添加一个框架,如 Glashammer (Werkzeug + Jinja2)通过使用事件为您简化此过程。许多函数可以在WSGI调用过程中连接到事件(例如,创建请求时),并且可以在该位置将东西放在模板命名空间中。

I should probably also add that a framework like Glashammer (Werkzeug+Jinja2) streamlines this process for you by using events. Many functions can connect to the events during the process of the WSGI call (for example, when a request is created) and they can put stuff in the template namespace at that point.

这篇关于使用Werkzeug和Jinja2的上下文处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆