1
0
mirror of https://github.com/etesync/server synced 2024-11-22 16:58:08 +00:00
etesync-server/etebase_fastapi/db_hack.py
Tom Hacohen 5b8f667e55 Cleanup django db connections before every request and every dependency.
This is instead of the commit we reverted in the previous commit.
The problem is that django keeps the connection per thread and it relies
on django itself to clean them up before/after connections.
We can't do this, because django is unaware of fastapi, so we have to
manage this ourselves.

The easiest way is to call it at the beginning of evenry route and every dep.
We need to do it for each because unfortunately fastapi may send them to
different worker threads.
2020-12-30 17:16:58 +02:00

28 lines
717 B
Python

"""
FIXME: this whole function is a hack around the django db limitations due to how db connections are cached and cleaned.
Essentially django assumes there's the django request dispatcher to automatically clean up after the ORM.
"""
import typing as t
from functools import wraps
from django.db import close_old_connections, reset_queries
def django_db_cleanup():
reset_queries()
close_old_connections()
def django_db_cleanup_decorator(func: t.Callable[..., t.Any]):
from inspect import iscoroutinefunction
if iscoroutinefunction(func):
return func
@wraps(func)
def wrapper(*args, **kwargs):
django_db_cleanup()
return func(*args, **kwargs)
return wrapper