In [1]:
import sqlalchemy
sqlalchemy.__version__
Out[1]:
In [2]:
import os
os.environ
Out[2]:
In [3]:
host = os.environ['DB_PORT_5432_TCP_ADDR']
port = os.environ['DB_PORT_5432_TCP_PORT']
In [4]:
from sqlalchemy import create_engine
engine = create_engine(
'postgresql://postgres@{}:{}/postgres'.format(host, port))
In [5]:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
In [6]:
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
In [7]:
User.__table__
Out[7]:
In [8]:
Base.metadata.create_all(engine)
In [9]:
ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
In [10]:
ed_user.name
Out[10]:
In [11]:
ed_user.password
Out[11]:
In [12]:
str(ed_user.id)
Out[12]:
In [13]:
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
In [14]:
session = Session()
In [15]:
session.add(ed_user)
In [16]:
our_user = session.query(User).filter_by(name='ed').first()
In [17]:
our_user
#<User(name='ed', fullname='Ed Jones', password='edspassword')>
Out[17]:
In [18]:
ed_user is our_user
#True
Out[18]:
In [19]:
session.add_all([
User(name='wendy', fullname='Wendy Williams', password='foobar'),
User(name='mary', fullname='Mary Contrary', password='xxg527'),
User(name='fred', fullname='Fred Flinstone', password='blah')])
In [20]:
ed_user.password = 'f8s7ccs'
In [21]:
session.dirty
#IdentitySet([<User(name='ed', fullname='Ed Jones', password='f8s7ccs')>])
Out[21]:
In [22]:
session.new
#IdentitySet([<User(name='wendy', fullname='Wendy Williams', password='foobar')>,
#<User(name='mary', fullname='Mary Contrary', password='xxg527')>,
#<User(name='fred', fullname='Fred Flinstone', password='blah')>])
Out[22]:
In [23]:
session.commit()
In [24]:
ed_user.id
Out[24]: