python3 flask中SQLAlchemy创建表的简单介绍

在flask的SQLAlchemy中创建表,也是存在 ForeignKey(一对多) 与 ManyToMany(多对多) 的存在,以下是在models中单表、一对多、多对多的创建方式。

models.py代码如下:

import datetime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,Text,ForeignKey,DateTime,UniqueConstraint,Index
from sqlalchemy.orm import relationship

Base = declarative_base()

# 【单表创建的示例】
class Users(Base):
    __tablename__ = 'users'
    id = Column(Integer,primary_key=True)
    name = Column(String(32),index=True)
    age = Column(Integer,default=18)
    email = Column(String(32),unique=True)  # unique = True 表示该字段中的值唯一
    ctime = Column(DateTime,default=datetime.datetime.now())
    extra = Column(Text,nullable=True)

    __table_args__ = (
        UniqueConstraint('id','name',name='unique_id_name'),  # 创建表中id和name字段的唯一索引,最后一个参数是索引名,注意前面要写name=
        Index('ix_name_email','name','email')   # 创建表中多个字段的普通索引
    )


# 【一对多示例】
# 表1
class Hobby(Base):
    __tablename__ = 'hobby'
    id = Column(Integer,primary_key=True)
    caption = Column(String(10),nullable=False,default='台球')

# 表2
class Person(Base):
    __tablename__ = 'person'
    nid = Column(Integer,primary_key=True)
    name = Column(String(32),index=True,nullable=True)
    # 创建一对多的关系
    hobby_id = Column(Integer,ForeignKey('hobby.id'))

    #   此字段不在表中生成,只是为了方便调用Hooby表;
    # 正向查找时可以直接用“hobby.”调用“Hobby”表中的字段。
    # 在hobby表中反向查找时可以用“pers”调用“Person”表中的字段。
    hobby = relationship('Hobby',backref='pers')


# 【多对多示例】
# 两表的关系表
class Server2Group(Base):
    __tablename__ = 'server2group'
    id = Column(Integer,primary_key=True,autoincrement=True)
    server_id = Column(Integer,ForeignKey('server.id'))
    group_id = Column(Integer,ForeignKey('group.id'))



# 表1
class Server(Base):
    __tablename__ = 'server'
    id = Column(Integer,primary_key=True,autoincrement=True)
    hostname = Column(String(15),nullable=True,unique=True)

    # 用于方便查找的标识
    groups = relationship('Group',secondary='server2group',backref='servers')

# 表2
class Group(Base):
    __tablename__ = 'group'
    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(32),nullable=True,unique=True)


def create_all():
    """
        根据类创建数据库表
        :return:
        """
    engine = create_engine(
        "mysql+pymysql://root:0p-0p-0p-@127.0.0.1:3306/test0621?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )

    Base.metadata.create_all(engine)


def drop_db():
    """
    根据类删除数据库表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:0p-0p-0p-@127.0.0.1:3306/test0621?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )

    Base.metadata.drop_all(engine)


if __name__ == '__main__':
    drop_db()
    create_all()
标签:SQLAlchemyFlaskPython 发布于:2019-10-24 03:59:34