FastAPI 数据库创建

# coding: utf8
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"

# 创建 SQLAlchemy 引擎, connect_args={"check_same_thread": False},启用多个线程, 仅用于SQLite,在其他数据库不需要它
engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)

# 创建SessionLocal类, 每个实例SessionLocal都会是一个数据库会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建一个Base类¶, 将用这个类继承,来创建每个数据库模型或类(ORM 模型)
Base = declarative_base()

# 数据库初始化,如果没有库或者表,会自动创建
Base.metadata.create_all(bind=engine)



# 创建数据库模型
from sqlalchemy import Boolean, Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship


class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True,index=True)
    email = Column(String, unique=True,index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=False)

    # 表示该表与其他表关联 例如: user.items 
    items = relationship('Item', back_populates="owner") 

class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String, index=True)
    owner_id = Column(Integer, ForeignKey("users.id"))

    # 例如: items__id  
    owner = relationship("User", back_populates="items")



from fastapi import FastAPI
app = FastAPI()

Last updated