-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
29 lines (22 loc) · 902 Bytes
/
Copy pathdatabase.py
File metadata and controls
29 lines (22 loc) · 902 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
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from dotenv import load_dotenv
import os
load_dotenv()
DB_URL = os.getenv('DATABASE_URL')
engine = create_engine(DB_URL)
# For every API request, a DB session is created and it ends when the response is returned to the client.
# Flask did it under the hood.
SessionLocal = sessionmaker( # Now SessionLocal is factory class to instantiate individual db objects
autocommit = False,
autoflush = False,
bind = engine
)
Base = declarative_base() # Base class which is inherited by every database models you write
# Dependency injection
def get_db():
db = SessionLocal() # opening the session
try:
yield db # yield keyword makes this a python generator function. It pauses this function and hand delivers the db session to route function
finally:
db.close()