imbolc / async-django-user

Using django user with async frameworks like aiohttp, starlette, etc.
11 stars 3 forks source link
aiohttp asyncio authorization django starlette

Async Django User

Using django user with async frameworks like aiohttp, starlette etc.

pip install async-django-session async-django-user

tl;dr

Take a look at registration / authorization examples for aiohttp + databases or starlette + asyncpg.

API

Backends

There's two ways of communicating to database available:

User

To fetch an user from db by its id stored in [django session] there's backend.get_user_from_session method:

user = backend.get_user_from_session(session)

It's lazy so the user data won't be actually fetched until you call its load method. It caches the result, so it's inexpensive to call it multiple times:

await user.load()

User provides dict interface to it's data (eg user["username"]) and a few methods:

Frameworks integration

There's built-in middlewares for a few async frameworks to automatically load user of the current request. Take a look at examples folder for:

Running examples

Running the examples you can see different frameworks using the same session and user data.

Install the requirements:

cd examples
pip install -r requirements.txt

Create database and tables:

createdb async_django_session
python django_app.py migrate

Create a user:

python django_app.py createsuperuser

Run aiohttp example which uses databases backend:

python aiohttp_app.py

Run starlette example which uses asyncpg backend:

python starlette_app.py

Run django example:

python django_app.py runserver