python-webservice/database.py

27 lines
640 B
Python
Raw Normal View History

2022-10-14 17:52:31 +00:00
# database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
try:
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
except ImportError as e:
raise ImportError(f"Failed to import pymysql as MySQLdb: {e}")
DATABASE_URL = "mysql+mysqldb://mysql:password@127.0.0.1/db"
db_engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=db_engine)
Base = declarative_base()
def get_db():
db = None
try:
db = SessionLocal()
yield db
finally:
db.close()