sqlalchemy: ORM (Object Relational Mapper) von Python. ORM ist kurz gesagt eine Bibliothek, die Relational DataBase wie ein Python-Objekt behandeln kann.
Installation
$ pip install SQLAlchemy
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
Wenn echo = True, wird das ausgegebene SQL im Protokoll ausgespuckt
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()
Weitere Informationen finden Sie unter Offizielles Tutorial. Es ist sehr gut organisiert.
Recommended Posts