sqlalchemy: ORM (Object Relational Mapper) made by python. ORM is, in a nutshell, a library that can treat Relational DataBase like a Python Object.
Installation
$ pip install SQLAlchemy
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
If echo = True, the issued SQL will be spit out in the log
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
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)
Base.metadata.create_all(engine)
database_setup.py
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Restaurant(Base):
__tablename__ = 'restaurant'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'name': self.name,
'id': self.id,
}
class MenuItem(Base):
__tablename__ = 'menu_item'
name = Column(String(80), nullable=False)
id = Column(Integer, primary_key=True)
description = Column(String(250))
price = Column(String(8))
course = Column(String(250))
restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
restaurant = relationship(Restaurant)
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'name': self.name,
'description': self.description,
'id': self.id,
'price': self.price,
'course': self.course,
}
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.create_all(engine)
database_setup.py
from sqlalchemy import create_engine
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantMenu.db')
Base.metadata.bind=engine
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
#create
new_restaurant = Restaurant(name='Pizza Palace')
session.add(new_restaurant)
session.commit()
#read
session.query(Restaurant).all()
#update
burger = session.query(MenuItem).filter_by(name = 'Burger').one()
burger.price = '$2.99'
session.add(burger)
session.commit()
#delete
ice_cream = session.query(MenuItem).filter_by(name = 'Ice Cream').one()
session.delete(ice_cream)
session.commit()
See Official Tutorial for details. It's very well organized.
Recommended Posts