DEV Community 👩‍💻👨‍💻


Posted on

My aiohttp and jinja2 app sample

Recently, I started to use aiohttp server and aiohttp_jinja2 for my personal project. It is very useful.

My python version is 3.8.2.

$ python --version
Python 3.8.2

# requirements.txt

pip install aiohttp[speedups]
pip install aiohttp_jinja
Enter fullscreen mode Exit fullscreen mode

Project directory is like below

└── app
    └── templates
        ├── index.html
        └── layout.html
Enter fullscreen mode Exit fullscreen mode

aiohttp_jinja and aiohttp Class Based View can be used like below example.


import logging
import pathlib
import sys

import jinja2
import aiohttp_jinja2
from aiohttp import web

class HomeHandler(web.View):

    async def get(self):
        return {}

    async def post(self):
        form = await
        return {"name":form['name']}

if __name__ == "__main__":


    app = web.Application()

    # setup jinja2 

    app.router.add_get('/', HomeHandler, name="index")
    app.router.add_post('/', HomeHandler)

Enter fullscreen mode Exit fullscreen mode
<!-- layout.html -->

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>aiohttp and jinja test</title>

    <h1>My aiohttp jinja demo</h1>

    {%block body%}{%endblock%}


Enter fullscreen mode Exit fullscreen mode
<!-- index.html -->
{% extends "layout.html" %}
{% set title = "Main" %}
{% block body %}

    <h2>Form test extended from layout.html</h2>

    <form method="POST" action="{{ url('index') }}">
        <input type="text" name="name" id="name"/>
        <input type="submit">

    {% if name %}

        <p>My name is {{ name }}</p>

    {% endif %}
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

prashantsengar profile image
Prashant Sengar

Great work! Way to go

kemurayama profile image
kemurayama Author

Thanks !

Head to your account's Settings to...

🌚 Enable dark mode
🔠 Change your default font
📚 Adjust your experience level to see more relevant content