好好百科

分享有趣又有用的知识

用户工具

站点工具


侧边栏

导航菜单

python:pypi:sqlalchemy

SQLAlchemy

database.py

from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from pytz import timezone
 
DATABASE_URI = 'postgres://user:password@host/database'
engine = create_engine(DATABASE_URI)  # 注:postsql依赖psycopg2-binary包
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
 
 
def _utcnow():
    return datetime.now(timezone('UTC'))
 
 
class Model(Base):
    __abstract__ = True
    id = Column(Integer, primary_key=True)
    created_datetime = Column(DateTime(timezone=True), default=_utcnow)
    updated_datetime = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)
 
 
def create_all():
    Base.metadata.create_all(engine)

models.py

from sqlalchemy import Column, Text
from database import Model, create_all
 
class Product(Model):
    __tablename__ = 'product'
    title = Column(Text)
 
create_all()

product.py

from database import session
from models import Product
 
# Create 
product = Product(title="Office Chair")  
session.add(product)  
session.commit()
 
# Read
products = session.query(Product)  
for product in products:  
    print(product.title)
 
# Update
product.title = "Sofa"  
session.commit()
 
# Delete
session.delete(product)  
session.commit()  
python/pypi/sqlalchemy.txt · 最后更改: 2019/08/22 16:08 由 老赵