DEV Community

kemurayama
kemurayama

Posted on

1 2

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
aiohttp[speedups]
aiohttp_jinja

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

Project directory is like below

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

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

# main.py

import logging
import pathlib
import sys

import jinja2
import aiohttp_jinja2
from aiohttp import web

@aiohttp_jinja2.template("index.html")
class HomeHandler(web.View):

    async def get(self):
        return {}

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


if __name__ == "__main__":

    logging.basicConfig(level=logging.DEBUG)

    app = web.Application()

    # setup jinja2 
    aiohttp_jinja2.setup(app,
        loader=jinja2.FileSystemLoader(
            'templates'
            ))

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


    web.run_app(app)
Enter fullscreen mode Exit fullscreen mode
<!-- layout.html -->

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

    <h1>My aiohttp jinja demo</h1>

    {%block body%}{%endblock%}

</body>
</html>

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">
    </form>

    {% if name %}

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

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

Collapse
 
prashantsengar profile image
Prashant Sengar

Great work! Way to go

Collapse
 
kemurayama profile image
kemurayama

Thanks !

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs