在使用 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/