代码之家  ›  专栏  ›  技术社区  ›  Messa

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

  •  0
  • Messa  · 技术社区  · 7 年前

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

    有类似的东西吗 json_response() ?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Messa    7 年前

    如果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)
    

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

    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)