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

How to return HTML response from aiohttp.web server?

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

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

如果字符串中已有 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)

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

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>')

Jinja2 模板

另一种选择是使用 Jinja2 template engine with aiohttp_jinja2:

# hello.html

<h1>Hello, {{ name }}!</h1>
# 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)

是的,非常简单,您只需阅读文件

from aiohttp import web


routes = web.RouteTableDef()
def html_response(document):
    s = open(document, "r")
    return web.Response(text=s.read(), content_type='text/html')

@routes.get('/')
async def index_handler(request):
    return html_response('index.html')


app = web.Application()
app.add_routes(routes)
web.run_app(app)