When building web applications and APIs with aiohttp in Python, you'll often need to return HTML content to the client. aiohttp makes this easy by allowing you to directly return HTML code and have it properly formatted in the response.
Setting the Response Type
By default, aiohttp will return responses as plain text. To tell it that you want to return HTML instead, set the
from aiohttp import web
async def handle(request):
return web.Response(
text="<html><body>Hello</body></html>",
content_type="text/html"
)
This will properly send the HTML code back to the client.
Returning Template Contexts
Often you won't want to directly write HTML code in your route handlers. Instead, you can use a template engine like Jinja to generate the HTML from a separate template file.
Here's an example using Jinja2:
import jinja2
from aiohttp import web
template = jinja2.Template("<html><body>{{ name }}</body></html>")
async def handle(request):
context = {"name": "John"}
return web.Response(
text=template.render(context),
content_type="text/html"
)
This keeps the code clean and maintains separation between logic and presentation.
Streaming Responses
For very large HTML responses, you may want to stream the output to avoid loading the entire string into memory. This can be done by passing an async generator to
async def handle(request):
async def stream():
yield "<html><body>Hello"
yield "World</body></html>"
return web.StreamResponse(status=200, content_type="text/html")
Conclusion
aiohttp provides a flexible API for returning HTML to clients. By setting the content type and using templates or response streaming, you can build robust web apps and sites. The key is keeping the HTML generation separate from the route logic.