-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
32 lines (23 loc) · 828 Bytes
/
Copy pathdatabase.py
File metadata and controls
32 lines (23 loc) · 828 Bytes
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
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://localhost/realtime_hub")
class _LazySessionFactory:
"""Defers engine creation until the first call.
This prevents importing this module from requiring the database driver
(e.g. psycopg2) to be installed just to run tests that never touch the
default PostgreSQL connection.
"""
_factory = None
def __call__(self):
if self._factory is None:
engine = create_engine(DATABASE_URL)
self._factory = sessionmaker(bind=engine, autocommit=False, autoflush=False)
return self._factory()
SessionLocal = _LazySessionFactory()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()