Skip to content

Instantly share code, notes, and snippets.

@jak010
Last active February 9, 2024 18:25
Show Gist options
  • Save jak010/555621bdfcc12fa63d8bddade26ab61d to your computer and use it in GitHub Desktop.
Save jak010/555621bdfcc12fa63d8bddade26ab61d to your computer and use it in GitHub Desktop.
[SAMPLE] SQLAlchemy Setup
from sqlalchemy.engine.url import URL
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
CORE = int(os.cpu_count())
DB_URL = URL.create(
drivername="mysql+pymysql",
username='root',
password="1234",
database="",
host="127.0.0.1",
port=1234
)
db_engine = engine.create_engine(
DB_URL,
pool_pre_ping=True,
pool_recycle=3600,
pool_size=5,
max_overflow=5,
pool_timeout=10,
echo=True
)
db_session: Session = scoped_session(sessionmaker(
bind=db_engine,
expire_on_commit=False,
autocommit=False,
autoflush=False
))
def transactional(func: Callable): # XXX: transactionl 임시구현, 이 방법(decorator)은 type hint가 적용이 안됨
@functools.wraps(func)
def _wrapper(*args, **kwargs):
try:
result = func(*args, **kwargs)
db_session.flush()
db_session.commit()
return result
except Exception as e:
db_session.rollback()
raise e
finally:
db_session.close()
return _wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment