diff options
author | pacien | 2021-07-25 21:53:59 +0200 |
---|---|---|
committer | pacien | 2021-07-25 21:53:59 +0200 |
commit | 7f11aa00673b0f77523db44969699c54289ace5b (patch) | |
tree | 77ed092b04460e263532d76843945a05a1229d58 /app/app_database.py | |
parent | 1a74f19cd68e3b7264621e7231475c6b25505e6d (diff) | |
download | uge_l2_rdbms_python_proto-7f11aa00673b0f77523db44969699c54289ace5b.tar.gz |
app: working web prototype
Diffstat (limited to 'app/app_database.py')
-rw-r--r-- | app/app_database.py | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/app/app_database.py b/app/app_database.py new file mode 100644 index 0000000..77f092a --- /dev/null +++ b/app/app_database.py | |||
@@ -0,0 +1,43 @@ | |||
1 | # UGE / L2 / Intro to relational databases / Python project prototype | ||
2 | # Author: Pacien TRAN-GIRARD | ||
3 | # Licence: EUPL-1.2 | ||
4 | |||
5 | from os import environ | ||
6 | from functools import partial | ||
7 | from contextlib import contextmanager | ||
8 | |||
9 | import psycopg2 | ||
10 | from psycopg2.extras import NamedTupleCursor | ||
11 | from psycopg2.extensions import ISOLATION_LEVEL_READ_COMMITTED | ||
12 | |||
13 | import embrace | ||
14 | from embrace import pool | ||
15 | |||
16 | |||
17 | # Connection to the PostgreSQL database server. | ||
18 | # Using a cursor which exposes result rows as named tuples for convenience. | ||
19 | # TODO: switch to psycopg3 and use asynchronous queries in handlers. | ||
20 | db_connect = partial( | ||
21 | psycopg2.connect, | ||
22 | environ['DATABASE_URL'], | ||
23 | cursor_factory=NamedTupleCursor) | ||
24 | |||
25 | db_pool = pool.ConnectionPool(db_connect, limit=4) | ||
26 | |||
27 | |||
28 | # Turn our annotated SQL queries into Python functions. | ||
29 | queries = embrace.module('./sql/', auto_reload=True) | ||
30 | |||
31 | |||
32 | @contextmanager | ||
33 | def db_transaction(isolation_level=ISOLATION_LEVEL_READ_COMMITTED): | ||
34 | """ | ||
35 | Get a connection from the connection pool and begin a transaction with the | ||
36 | given isolation level. The transaction is automatically rolled back if an | ||
37 | uncaught exception escapes the current context. Otherwise, it is | ||
38 | automatically committed when finishing with no error. | ||
39 | """ | ||
40 | with db_pool.connect() as conn: | ||
41 | conn.set_isolation_level(isolation_level) | ||
42 | with queries.transaction(conn) as tx: | ||
43 | yield tx | ||