Skip to content

Instantly share code, notes, and snippets.

@senaps
Created January 29, 2019 11:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save senaps/5fd9a7372d882ea783a115579d739cdf to your computer and use it in GitHub Desktop.
Save senaps/5fd9a7372d882ea783a115579d739cdf to your computer and use it in GitHub Desktop.
from contextlib import contextmanager
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, DateTime, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
Base = declarative_base()
engine = create_engine(database_url[0], echo=False)
@contextmanager
def session_scope():
"""Provide a transactional scope around a series of operations."""
session = Session(bind=engine)
try:
yield session
except:
session.rollback()
raise
finally:
session.close()
class Names(Base):
....
..... DEFINE MODELS AS NORMAL ......
from models import session_scope, Names, <ModelNames we want to use>
with session_scope() as session:
names = session.query(Names).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment