30 lines
887 B
Python
30 lines
887 B
Python
import os
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
|
|
config = {}
|
|
for key in ["POSTGRES_USER","POSTGRES_PASSWORD","POSTGRES_DB","POSTGRES_HOST","POSTGRES_PORT"]:
|
|
config[key.lower().replace("postgres_","")] = os.environ.get(key,"")
|
|
|
|
if config["user"] and config["password"]:
|
|
config["auth"] = f"{config['user']}:{config['password']}"
|
|
elif config["user"]:
|
|
config["auth"] = config['user']
|
|
else:
|
|
raise ValueError("Username is required.")
|
|
|
|
if not config["db"]:
|
|
raise ValueError("Db is invalid.")
|
|
|
|
if not config["port"]:
|
|
config["port"] = ":5432"
|
|
elif ":" not in str(config["port"]):
|
|
config["port"] = f":{str(config["port"])}"
|
|
|
|
engine = create_engine(f"postgresql://{config['auth']}@{config['host']}{config['port']}/{config['db']}", echo=False)
|
|
|
|
SessionLocal = sessionmaker(bind=engine)
|
|
|
|
Base = declarative_base()
|