Skip to content

Instantly share code, notes, and snippets.

@jvanasco
Created November 6, 2014 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvanasco/4ed7194996357e18e26c to your computer and use it in GitHub Desktop.
Save jvanasco/4ed7194996357e18e26c to your computer and use it in GitHub Desktop.
template idea for sqlalchemy sscce
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
# Use this file to build your own SSCCE
# SSCCE = Short, Self Contained, Correct (Compatible) Example
# see http://sscce.org/
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Standard imports
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import deferred, class_mapper
from sqlalchemy import Integer, String, Text, Binary, Column, ForeignKey
from sqlalchemy import inspect
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# You probably don't need to overwrite this
Base = declarative_base()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Define some models that inherit from Base
class Foo(Base):
__tablename__ = 'foo'
id = Column(Integer, primary_key=True)
class Bar(Base):
__tablename__ = 'bar'
id = Column(Integer, primary_key=True)
class Foo2Bar(Base):
__tablename__ = 'foo_2_bar'
id_foo = Column(Integer, ForeignKey("foo.id"), primary_key=True)
id_bar = Column(Integer, ForeignKey("bar.id"), primary_key=True)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# we'll use sqlite+memory to handle this
# if your issue is backend specific, then the engine will need to be different
engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# you shouldn't change these 2 line
sessionFactory = sessionmaker(bind=engine)
s = sessionFactory()
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Start your example here:
f = Foo(id=1)
s.add(f)
b = Bar(id=2)
s.add(b)
s.flush()
f2b = Foo2Bar(id_foo=1, id_bar=2)
s.add(f2b)
s.commit()
a = s.query(Foo).get(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment