连接数据库

sqlalchemy

  1. from sqlalchemy import create_engine
  2. from sqlalchemy.ext.declarative import declarative_base
  3. from sqlalchemy.orm import sessionmaker
  4. # 声明地址
  5. SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
  6. # SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
  7. # 声明引擎
  8. engine = create_engine(
  9. SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
  10. )
  11. # 声明会话
  12. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  13. # 建立客户端
  14. Base = declarative_base()

ORM

  1. from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
  2. from sqlalchemy.orm import relationship
  3. from .database import Base
  4. class User(Base):
  5. __tablename__ = "users"
  6. id = Column(Integer, primary_key=True, index=True)
  7. email = Column(String, unique=True, index=True)
  8. hashed_password = Column(String)
  9. is_active = Column(Boolean, default=True)
  10. items = relationship("Item", back_populates="owner")
  11. class Item(Base):
  12. __tablename__ = "items"
  13. id = Column(Integer, primary_key=True, index=True)
  14. title = Column(String, index=True)
  15. description = Column(String, index=True)
  16. owner_id = Column(Integer, ForeignKey("users.id"))
  17. owner = relationship("User", back_populates="items")

当访问中的属性items时User(如中的)my_user.items,它将具有一个ItemSQLAlchemy模型列表(来自items表),该模型具有指向users表中该记录的外键。
当您访问时my_user.items,SQLAlchemy实际上会从items表中的数据库中获取项目,并在此处填充它们。
并且当访问中的属性owner时Item,它将包含表中的UserSQLAlchemy模型users。它将使用owner_id属性/列及其外键来了解要从users表中获取哪个记录。