如何从 aiohttp.web 服务器返回 HTML 响应?

Mes*_*ssa 3 python aiohttp

如何从 aiohttp.web 处理程序返回 HTML 页面?

有没有类似于json_response() 的东西?

Mes*_*ssa 9

如果您已经在字符串中包含 HTML:

from aiohttp import web

routes = web.RouteTableDef()

@routes.get('/')
async def index_handler(request):
    return web.Response(
        text='<h1>Hello!</h1>',
        content_type='text/html')

app = web.Application()
app.add_routes(routes)
# or instead of using RouteTableDef:
# app.router.add_get('/', index_handler)

web.run_app(app)
Run Code Online (Sandbox Code Playgroud)

html_response()aiohttp中没有,但当然您可以创建自己的助手:

def html_response(text):
    return web.Response(text=text, content_type='text/html')

@routes.get('/')
async def index_handler(request):
    return html_response('<h1>Hello!</h1>')
Run Code Online (Sandbox Code Playgroud)

Jinja2 模板

另一种选择是将Jinja2模板引擎与aiohttp_jinja2一起使用:

# hello.html

<h1>Hello, {{ name }}!</h1>
Run Code Online (Sandbox Code Playgroud)
# my_web_app.py

from aiohttp import web
import aiohttp_jinja2
import jinja2
from pathlib import Path

here = Path(__file__).resolve().parent

@aiohttp_jinja2.template('hello.html')
def index_handler(request):
    return {'name': 'Andrew'}

app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(str(here)))
app.router.add_get('/', index_handler)

web.run_app(app)
Run Code Online (Sandbox Code Playgroud)