Skip to content

Instantly share code, notes, and snippets.

@alvesjnr
Created June 2, 2011 22:32
Show Gist options
  • Save alvesjnr/1005481 to your computer and use it in GitHub Desktop.
Save alvesjnr/1005481 to your computer and use it in GitHub Desktop.
First example using sqlalchemy
import sqlalchemy
engine = sqlalchemy.create_engine('sqlite:///:memory:', echo=False)
from sqlalchemy.ext.declarative import declarative_base
from Crypto.Hash import SHA256
from sqlalchemy.orm import relationship, backref
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
name = sqlalchemy.Column(sqlalchemy.String)
fullname = sqlalchemy.Column(sqlalchemy.String)
password = sqlalchemy.Column(sqlalchemy.String)
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = SHA256.new(password).hexdigest()
def __repr__(self):
return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password[:10]+'...')
class Address(Base):
__tablename__ = 'addresses'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
email_address = sqlalchemy.Column(sqlalchemy.String, nullable=False)
user_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey('users.id'))
user = relationship("User", backref=backref('addresses', order_by=id))
def __init__(self, email_address):
self.email_address = email_address
def __repr__(self):
return "<Address('%s')>" % self.email_address
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)
address = Address('[email protected]')
user = User('ed', 'Ed Jones', 'edspassword')
user.addresses=[address]
session.add(user)
user = User('ze', 'Jose Dores', 'zepassword')
session.add(user)
session.commit()
def can_access(username, password):
user = session.query(User).filter_by(name=username).first()
if not user:
raise KeyError('%s user doesnt exist' % username)
if user.password == SHA256.new(password).hexdigest():
return True
return False
"""query with join"""
print session.query(User).join(Address).filter(Address.email_address=="[email protected]").all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment