python - 使用带有 View 函数的 webapp2 微框架时如何呈现模板?

标签 python google-app-engine python-2.7 webapp2

我正在使用 webapp2 指南中描述的 webapp2 微框架 ( http://webapp-improved.appspot.com/guide/handlers.html ):

import webapp2

class WSGIApplication(webapp2.WSGIApplication):
    def __init__(self, *args, **kwargs):
        super(WSGIApplication, self).__init__(*args, **kwargs)
        self.router.set_dispatcher(self.__class__.custom_dispatcher)

    @staticmethod
    def custom_dispatcher(router, request, response):
        rv = router.default_dispatcher(request, response)
        if isinstance(rv, basestring):
            rv = webapp2.Response(rv)
        elif isinstance(rv, tuple):
            rv = webapp2.Response(*rv)
        return rv

    def route(self, *args, **kwargs):
        def wrapper(func):
            self.router.add(webapp2.Route(handler=func, *args, **kwargs))
            return func
        return wrapper

然后我定义我的 View 函数:

import micro_webapp2

app = micro_webapp2.WSGIApplication()

@app.route('/')
def hello_handler(request, *args, **kwargs):
    return 'Hello, world!'

相反,我想呈现模板、调用重定向并使用 webapp2 session 扩展。

使用 webapp2 微框架时应该怎么做?

最佳答案

回复:模板

看起来 webapp2 似乎没有内置模板引擎。然而,有很多非常高质量的 Python 模板系统。一些最受欢迎的包括 jinja2 , django-templates , 和 Pystache .

如果您计划部署到谷歌应用引擎,您可能需要选择 Django 模板或 Jinja2,因为它们是 both supported out of the box :

我推荐 jinja2,因为它很容易上手,有 really good documentation ,并且效果非常好(虽然我以前使用过 django 和 Pystache,但两者都很棒)。

Jinja2 有一个 getting started guide这应该可以帮助您快速入门。一旦你安装了 Jinja2,使用它应该只是简单地制作一个合适的"template"目录,其中包含一个模板。说“hello.html”:

<!doctype html>
<html><head><title>Hello {{ who }}</title></head>
<body><h1>Hello {{ who }}</h1></body>
</html>

让你的 View 看起来像这样:

import micro_webapp2
from jinja2 import Environment, PackageLoader

app = micro_webapp2.WSGIApplication()
env = Environment(loader=PackageLoader('my_application_name', 'templates'))

@app.route('/')
def hello_handler(request, *args, **kwargs):
    template = env.get_template('hello.html')
    return template.render(who='world')

希望对你有帮助

关于python - 使用带有 View 函数的 webapp2 微框架时如何呈现模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15676351/

相关文章:

python - 在Python中传递锁

python - 需要帮助的一个简单的python错误

python - 如何在 Python 中匹配字符串或字符的开头

java - JDO 查询中的多个类

python-2.7 - 给定所需的分布和经验采样生成随机数

django - Procfile 在 Heroku 中声明类型 -> (none)

python - 使用 REGEX 分割字符串

python - 如何在两个字符串之间输入文本?

python - Google App Engine Python If Else 在 Html 模板中的用法

python - UnicodeDecodeError : 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)