python - AIOHTTP Server - 用于引发条件的 Jinja 模板

标签 python python-3.x error-handling jinja2 aiohttp

在使用 AIOHTTP Web 创建站点时,我可能会定义一个路由并引发如下错误:

async def index(request):
    if some_error_happened:
        raise web.HTTPException(body=b'Some error happened.')
    context = {'page_title': "My Site"}
    response = aiohttp_jinja2.render_template('index.html', request, context)
    return response

这将显示我为 body 指定的文本但是我怎样才能像普通路线一样使用 Jinja2 呢?

我找到了模块 jinja2_error但我看不到如何在 aiohttp 路由的上下文中使用它。

最佳答案

使用aiohttp_jinja2.render_string :

async def index(request):
    if some_error_happened:
        raise web.HTTPBadRequest(
            text=aiohttp_jinja2.render_template(
                'index.html', 
                request, 
                {"error": "Some error happened"},
            )
        )
    context = {'page_title': "My Site"}
    response = aiohttp_jinja2.render_template('index.html', request, context)
    return response

关于python - AIOHTTP Server - 用于引发条件的 Jinja 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60086355/

相关文章:

python - 有没有更优雅的方式来读取 CSV 列并与记录 ID 合并?

jquery - Web API和jQuery ajax没有收到正确的错误

javascript - 如何在 Django 管理中选择单选按钮时隐藏/显示字段?

python - 如何提取文本中每个可能的日期?

python - 如何使用 python kubernetes 客户端读取 Kubernetes 部署

python - 如何更改 python 中的错误消息?

django - 如何显示错误消息Django

haskell - Haskell类型错误消息

python - 带有词典字典的 Bokeh 表

python - 尽管规范相同,但为什么不同 Linux 云提供商设置的 Python 线程平均负载会有所不同?