-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
34 lines (26 loc) · 873 Bytes
/
database.py
File metadata and controls
34 lines (26 loc) · 873 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
33
34
import os
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
try:
from dotenv import load_dotenv
except ImportError:
load_dotenv = None
if load_dotenv:
load_dotenv()
else:
env_file = Path(__file__).resolve().parent / ".env"
if env_file.exists():
for line in env_file.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
if key.strip() == "DATABASE_URL" and not os.getenv("DATABASE_URL"):
os.environ["DATABASE_URL"] = value.strip().strip('"').strip("'")
break
db_url = os.getenv("DATABASE_URL")
if not db_url:
raise ValueError("DATABASE_URL is not set. Add it to your .env file.")
engine = create_engine(db_url, echo=True)
session = sessionmaker(autocommit=False, autoflush=False, bind=engine)