Messa
Messa

Reputation: 25191

How to return HTML response from aiohttp.web server?

How can I return HTML page from an aiohttp.web handler?

Is there something similar to json_response()?

Upvotes: 6

Views: 12238

Answers (2)

piderking
piderking

Reputation: 21

Yes it is super easy you just have to read the file

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)

Upvotes: 2

Messa
Messa

Reputation: 25191

If you have the HTML already in a string:

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)

There is no html_response() in aiohttp, but of course you can create your own helper:

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 templates

Another option is to use 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)

Upvotes: 16

Related Questions