diff options
author | Frédéric Mangano-Tarumi <fmang@mg0.fr> | 2020-06-08 20:16:36 +0200 |
---|---|---|
committer | Lukas Fleischer <lfleischer@archlinux.org> | 2021-02-20 17:24:30 +0100 |
commit | c77e9d1de0d14253ab3c3b958f459b04b233aeb8 (patch) | |
tree | 983853ceefeb442112383023930e667bcb8fccf1 /aurweb | |
parent | a5554c19a9712ede5fe5a996bd1bec11cfc9f66a (diff) | |
download | aur-c77e9d1de0d14253ab3c3b958f459b04b233aeb8.tar.gz aur-c77e9d1de0d14253ab3c3b958f459b04b233aeb8.tar.xz |
Integrate SQLAlchemy into FastAPI
Signed-off-by: Lukas Fleischer <lfleischer@archlinux.org>
Diffstat (limited to 'aurweb')
-rw-r--r-- | aurweb/db.py | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/aurweb/db.py b/aurweb/db.py index 1ccd9a07..02aeba38 100644 --- a/aurweb/db.py +++ b/aurweb/db.py @@ -10,6 +10,8 @@ except ImportError: import aurweb.config +engine = None # See get_engine + def get_sqlalchemy_url(): """ @@ -38,6 +40,34 @@ def get_sqlalchemy_url(): raise ValueError('unsupported database backend') +def get_engine(): + """ + Return the global SQLAlchemy engine. + + The engine is created on the first call to get_engine and then stored in the + `engine` global variable for the next calls. + """ + from sqlalchemy import create_engine + global engine + if engine is None: + engine = create_engine(get_sqlalchemy_url(), + # check_same_thread is for a SQLite technicality + # https://fastapi.tiangolo.com/tutorial/sql-databases/#note + connect_args={"check_same_thread": False}) + return engine + + +def connect(): + """ + Return an SQLAlchemy connection. Connections are usually pooled. See + <https://docs.sqlalchemy.org/en/13/core/connections.html>. + + Since SQLAlchemy connections are context managers too, you should use it + with Python’s `with` operator, or with FastAPI’s dependency injection. + """ + return get_engine().connect() + + class Connection: _conn = None _paramstyle = None |