My aiohttp and jinja2 app sample

kemurayama

kemurayama

Posted on May 9, 2020

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
💖 💪 🙅 🚩
kemurayama
kemurayama

Posted on May 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related