【FastAPI 學習 二】SqlAlchemy Model模型類
阿新 • • 發佈:2020-12-26
FastAPI SqlAlchemy ORM Model
本系列部落格是配合Vue開發一套後臺管理系統,對應的Vue教程見
FastAPI 使用 SqlAlchemy建立models
檔案目錄
| |____db // 資料庫資料夾 | | |______init__.py | | |____session.py // 建立 SessionLocal 物件 | | |____base_class.py // model基礎模組 如通用欄位 | | |____base.py // 匯出全部models 給alembic遷移用 | |____models // 專案models 檔案(我沒像django那樣放到各模組下面,單獨抽出來了) | | |______init__.py | | |____auth.py // 使用者許可權相關的 | | |____goods.py // 各專案模組 商品模組
SqlAlchemy SessionLocal物件
在session.py
檔案生成 SessionLocal物件
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from app.core.config import settings engine = create_engine(settings.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Model Base類
在base_class.py
檔案中生成基礎的Model Base類
新增通用的欄位 設定表名字格式
from typing import Any from datetime import datetime from sqlalchemy import Column, Integer, DateTime from sqlalchemy.ext.declarative import as_declarative, declared_attr @as_declarative() class Base: # 通用的欄位 id: Any create_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="建立時間") update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新時間") is_delete = Column(Integer, default=0, comment="邏輯刪除:0=未刪除,1=刪除") __name__: str # Generate __tablename__ automatically @declared_attr def __tablename__(cls) -> str: import re # 如果沒有指定__tablename__ 則預設使用model類名轉換表名字 name_list = re.findall(r"[A-Z][a-z\d]*", cls.__name__) # 表明格式替換成_格式 如 MallUser 替換成 mall_user return "_".join(name_list).lower()
各模組Model類
比如使用者模組 models/auth.py
建立了兩個model 一個使用者,一個角色
import uuid
from sqlalchemy import Boolean, Column, Integer, String, VARCHAR, BIGINT
from app.api.db.base_class import Base
def gen_id():
return uuid.uuid4().hex
class AdminUser(Base):
"""
管理員使用者表
"""
__tablename__ = "admin_user"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(String(32), default=gen_id, comment="使用者id")
email = Column(String(128), unique=True, index=True, nullable=False, comment="郵箱")
phone = Column(VARCHAR(16), unique=True, index=True, nullable=True, comment="手機號")
nickname = Column(String(128), comment="使用者暱稱")
avatar = Column(String(256), comment="使用者頭像")
hashed_password = Column(String(128), nullable=False, comment="密碼")
is_active = Column(Boolean(), default=False, comment="郵箱是否啟用")
role_id = Column(Integer, comment="角色表")
class AdminRole(Base):
"""
簡單的使用者角色表設計
"""
role_id = Column(Integer, primary_key=True, index=True, comment="角色Id")
role_name = Column(String(64), comment="角色名字")
permission_id = Column(BIGINT, comment="許可權ID")
re_mark = Column(String(128), comment="備註資訊")
匯出方便遷移
把所有的model匯入到 db/base.py
檔案, 方便 Alembic 遷移表
from app.api.db.base_class import Base # noqa
from app.api.models.auth import AdminUser, AdminRole
本章程式碼 GitHub地址