SQLAlchemy-Utils

因爲sqlalchemy中沒有提供choice方法,因此藉助SQLAlchemy-Utils組件提供的choice方法。mysql

安裝:sql

pip3 install sqlalchemy_utils

示例:數據庫

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import Integer, String
from sqlalchemy import create_engine
from sqlalchemy_utils import ChoiceType

Base = declarative_base()


class UserInfo(Base):
    __tablename__ = "userinfo"

    id = Column(Integer, primary_key=True)
    name = Column(String(16), index=True, unique=True, nullable=False, autoincrement=True)
    gender_choices = (
        (0, ""),
        (1, ""),
        (2, "保密")
    )
    gender = Column(ChoiceType(gender_choices, Integer()))

    __table_args__ = {
        "mysql_engine": "Innodb",
        "mysql_charset": "utf8",
    }


def init_db():
    """根據類建立數據庫表"""
    engine = create_engine(
        "mysql+pymysql://root:""@127.0.0.1:3306/sqlalchemy_db?charset=utf8",
        max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
        pool_size=5,     # 鏈接池大小
        pool_timeout=20, # 池中沒有鏈接最多等待的時間,不然報錯
        pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
    )
    Base.metadata.create_all(engine)


def drop_db():
    """根據類刪除數據庫表"""
    engine = create_engine(
        "mysql+pymysql://root:""@127.0.0.1:3306/sqlalchemy_db?charset=utf8",
        max_overflow=0,
        pool_size=5,
        pool_timeout=20,
        pool_recycle=-1
    )
    Base.metadata.drop_all(engine)


if __name__ == "__main__":
    drop_db()
    init_db()
models.py
from models import UserInfo
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(
    "mysql+pymysql://root:""@127.0.0.1:3306/sqlalchemy_db?charset=utf8",
    max_overflow=0,  # 超過鏈接池大小外最多建立的鏈接
    pool_size=5,     # 鏈接池大小
    pool_timeout=20, # 池中沒有鏈接最多等待的時間,不然報錯
    pool_recycle=-1  # 多久以後對線程池中的線程進行一次鏈接的回收(重置)
)
SessionFactory = sessionmaker(bind=engine)
session = SessionFactory()

ret = session.query(UserInfo).all()
for row in ret:
    print(row.id, row.name, row.gender.value)
# 1 pd 男
# 2 pq 保密
View Code
本站公眾號
   歡迎關注本站公眾號,獲取更多信息