准备数据

 1 from sqlalchemy.ext.declarative import declarative_base
 2 from sqlalchemy import Column
 3 from sqlalchemy import Integer, String, Text, Date, DateTime, ForeignKey, UniqueConstraint, Index
 4 from sqlalchemy import create_engine
 5 from sqlalchemy.orm import relationship
 6 
 7 Base = declarative_base()
 8 
 9 
10 class Depart(Base):
11     __tablename__ = 'depart'
12     id = Column(Integer, primary_key=True)
13     title = Column(String(32), index=True, nullable=False)
14 
15 
16 class Users(Base):
17     __tablename__ = 'users'
18 
19     id = Column(Integer, primary_key=True)
20     name = Column(String(32), index=True, nullable=False)
21     depart_id = Column(Integer, ForeignKey("depart.id"))
22 
23     # 用于链表操作 与表的创建无关
24     dp = relationship("Depart", backref='pers')
25 
26 
27 class Student(Base):
28     __tablename__ = 'student'
29     id = Column(Integer, primary_key=True)
30     name = Column(String(32), index=True, nullable=False)
31 
32     course_list = relationship('Course', secondary='student2course', backref='student_list')
33 
34 
35 class Course(Base):
36     __tablename__ = 'course'
37     id = Column(Integer, primary_key=True)
38     title = Column(String(32), index=True, nullable=False)
39 
40 
41 class Student2Course(Base):
42     __tablename__ = 'student2course'
43     id = Column(Integer, primary_key=True, autoincrement=True)
44     student_id = Column(Integer, ForeignKey('student.id'))
45     course_id = Column(Integer, ForeignKey('course.id'))
46 
47     __table_args__ = (
48         UniqueConstraint('student_id', 'course_id', name='uix_stu_cou'),  # 联合唯一索引
49         # Index('ix_id_name', 'name', 'extra'),                          # 联合索引
50     )
51 
52 
53 def create_all():
54     engine = create_engine(
55         "mysql+pymysql://root:123456@192.168.226.150:3306/flask_demo?charset=utf8",
56         max_overflow=0,  # 超过连接池大小外最多创建的连接
57         pool_size=5,  # 连接池大小
58         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
59         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
60     )
61 
62     Base.metadata.create_all(engine)
63 
64 
65 def drop_all():
66     engine = create_engine(
67         "mysql+pymysql://root:123456@192.168.226.150:3306/flask_demo?charset=utf8",
68         max_overflow=0,  # 超过连接池大小外最多创建的连接
69         pool_size=5,  # 连接池大小
70         pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
71         pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
72     )
73     Base.metadata.drop_all(engine)
74 
75 
76 if __name__ == '__main__':
77     # drop_all()
78     create_all()
models.py

相关文章:

  • 2021-08-02
  • 2021-07-19
  • 2021-12-21
  • 2022-12-23
  • 2021-09-13
  • 2022-02-19
猜你喜欢
  • 2022-01-24
  • 2021-07-01
  • 2021-09-14
  • 2022-12-23
  • 2021-12-15
  • 2021-08-25
  • 2021-11-17
相关资源
相似解决方案