google-app-engine - webapp2 jinja2 context_processor

标签 google-app-engine jinja2 webapp2

我正在 GAE、webapp2、jinja2 上构建一个项目,我使用 engineauth用于授权。我需要类似 Django 的 context_processor 的东西,以便在模板中使用来自 webapp2.request 的 session 、用户和其他一些变量。请帮我解决这个问题。

最佳答案

有很多方法可以实现这一目标。

最简单的方法可能如下所示:

def extra_context(handler, context=None):
    """
    Adds extra context.
    """

    context = context or {}

    # You can load and run various template processors from settings like Django does.
    # I don't do this in my projects because I'm not building yet another framework
    # so I like to keep it simple:

    return dict({'request': handler.request}, **context)


# --- somewhere in response handler ---
def get(self):
    my_context = {}
    template = get_template_somehow()
    self.response.out.write(template.render(**extra_context(self, my_context))

我喜欢当我的变量位于模板全局变量中时,我可以在模板小部件中访问它们,而不必在模板中传递一堆变量。所以我这样做:

def get_template_globals(handler):
    return {
        'request': handler.request,
        'settings': <...>
    }


class MyHandlerBase(webapp.RequestHandler):
    def render(self, context=None):
        context = context or {}
        globals_ = get_template_globals(self)
        template = jinja_env.get_template(template_name, globals=globals_)
        self.response.out.write(template.render(**context))

还有其他方法:Context processor using Werkzeug and Jinja2

关于google-app-engine - webapp2 jinja2 context_processor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11445772/

相关文章:

python - 我应该如何处理 Google App Engine 中的循环导入?

python - App Engine 配额中的电子邮件管理员是什么?

python - 导入错误: cannot import name is_python_keyword

python - 如何在 Python/Ansible 中用模式 {{ '{{' }}/{{ '}}' }} 替换左大括号和右大括号 {{ }}

python - GAE/webapp2 : Serving Excel file created by script using xlwt

Python:创建类实例

google-app-engine - Google App Engine 从父文件夹导入库

google-app-engine - 如果使用 Twig/Objectify/etc,是否可以从 GAE 项目中消除与 JDO/JPA 相关的 JAR?

json - 如何从 ansible 中的模板编写漂亮的 JSON 文件?

python - 应用引擎 : What is the lifetime of the app-level registry in webapp2