gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:13:10 26 4
gpt4 key购买 nike

如何从 aiohttp.web 处理程序返回 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模板引擎 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)

关于python - 如何从 aiohttp.web 服务器返回 HTML 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com