-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
49 lines (38 loc) · 1.05 KB
/
db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from valkey.asyncio import ConnectionPool, Valkey
from config import POSTGRES_URL, VALKEY_URL
_db_engine = create_async_engine(
POSTGRES_URL,
query_cache_size=128,
pool_size=10,
max_overflow=-1,
)
@asynccontextmanager
async def db_read():
"""
Get a database session for reading.
"""
async with AsyncSession(
_db_engine,
expire_on_commit=False,
close_resets_only=False,
) as session:
yield session
@asynccontextmanager
async def db_write():
"""
Get a database session for writing, automatically committing on exit.
"""
async with AsyncSession(
_db_engine,
expire_on_commit=False,
close_resets_only=False,
) as session:
yield session
await session.commit()
_valkey_pool = ConnectionPool().from_url(VALKEY_URL)
@asynccontextmanager
async def valkey():
async with Valkey(connection_pool=_valkey_pool) as r:
yield r