那些年被我坑过的Python——牵一发动全身 第十一章MySQL、ORM

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 __Author__ = "Zhang Xuyao"
4 
5 from sqlalchemy import create_engine
6 
7 # engine = create_engine("mysql+pymysql://root:123123@localhost/attendance?charset=utf8", echo=True)
8 engine = create_engine("mysql+pymysql://root:123123@localhost/attendance?charset=utf8")
engine
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 __Author__ = "Zhang Xuyao"
 4 
 5 from sqlalchemy.ext.declarative import declarative_base
 6 from settings import db_settings
 7 from sqlalchemy import Table, Column, Integer, String, Enum, DATE, ForeignKey, PrimaryKeyConstraint
 8 from sqlalchemy.orm import relationship
 9 
10 Base = declarative_base()
11 
12 teacherBatch_t = Table('tbt', Base.metadata,
13                        Column('batch_name', String(64), ForeignKey('batch.name')),
14                        Column('teacher_id', String(64), ForeignKey('teacher.id'))
15                        )
16 
17 studentBatch_t = Table('sbt', Base.metadata,
18                        Column('batch_name', String(64), ForeignKey('batch.name')),
19                        Column('student_qq', String(64), ForeignKey('student.qq'))
20                        )
21 
22 
23 class Teacher(Base):
24     __tablename__ = 'teacher'
25     id = Column(String(64), primary_key=True)
26     name = Column(String(64), nullable=False)
27     password = Column(String(64), nullable=False, default='321cba')
28 
29     # tstudents = relationship('Student', secondary=task_t, backref='teachers')
30     tbatchs = relationship('Batch', secondary=teacherBatch_t, backref='teachers')
31 
32     def __repr__(self):
33         return self.name
34 
35 
36 class Student(Base):
37     __tablename__ = 'student'
38     qq = Column(String(64), primary_key=True)
39     name = Column(String(64), nullable=False)
40     password = Column(String(64), nullable=False, default='321cba')
41 
42     # steachers = relationship('Teacher', secondary=task_t, backref='students')
43     sbatchs = relationship('Batch', secondary=studentBatch_t, backref='students')
44 
45     def __repr__(self):
46         return self.name
47 
48 
49 # 课程批次(班级)name为批次如python14期,courseType为类型如python
50 class Batch(Base):
51     __tablename__ = 'batch'
52     name = Column(String(64), primary_key=True)
53     courseType = Column(String(64), nullable=False)
54 
55     def __repr__(self):
56         return self.name + self.courseType
57 
58 
59 class Task(Base):
60     __tablename__ = 'task'
61     batch_name = Column(String(64), ForeignKey('batch.name'))
62     date = Column(DATE, nullable=False)
63     student_qq = Column(String(64), ForeignKey('student.qq'))
64 
65     status = Column(Enum('at', 'ab', 'va', 'ot'),
66                     default='ab', nullable=False)
67     score = Column(Integer,
68                    default=0, nullable=False)
69     teacher_id = Column(String(64), ForeignKey('teacher.id'))
70 
71     comment = Column(String(1024))
72     task_pk = PrimaryKeyConstraint(batch_name, student_qq, date)
73 
74     student = relationship('Student', backref='tasks')
75     teacher = relationship('Teacher', backref='tasks')
76 
77 
78 # 父类调用所有的子类实现表结构的创建#####
79 
80 
81 # Base.metadata.drop_all(db_settings.engine)  # 删除表结构
82 Base.metadata.create_all(db_settings.engine)  # 创建表结构
tables relationship
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 __Author__ = "Zhang Xuyao"
 4 
 5 from settings import db_tables as dbt
 6 from settings import db_settings
 7 from sqlalchemy.orm import sessionmaker
 8 from sqlalchemy import desc,func
 9 import datetime
10 
11 Session_class = sessionmaker(bind=db_settings.engine)  # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
12 db = Session_class()  # 生成session实例
13 
14 
15 def teacherAuth(id, password):
16     obj = db.query(dbt.Teacher).filter(dbt.Teacher.id == id).first()
17     if not obj:
18         return False
19     if password == obj.password:
20         # print("got it")
21         return obj
22     else:
23         return False
24 
25 def studentAuth(qq, password):
26     obj = db.query(dbt.Student).filter(dbt.Student.qq == qq).first()
27     if not obj:
28         return False
29     if password == obj.password:
30         # print("got it")
31         return obj
32     else:
33         return False
34 
35 
36 def addTeacher(id, name, password='abc123'):
37     obj = dbt.Teacher(id=id, name=name, password=password)
38     db.add(obj)
39     db.commit()
40     return obj
41 
42 
43 def batchBindTeacher(id, name, password):
44     pass
45 
46 
47 def addStudent(qq, name, password='abc123'):
48     obj = dbt.Student(qq=qq, name=name, password=password)
49     db.add(obj)
50     db.commit()
51     return obj
52 
53 
54 def batchBindStudent(id, name, password):
55     pass
56 
57 
58 def addBatch(name, courseType):
59     obj = dbt.Batch(name=name, courseType=courseType)
60     db.add(obj)
61     db.commit()
62     return obj
63 
64 
65 def addTask(date, score='N/A', status='absent'):
66     pass
67 
68 
69 if __name__ == '__main__':
70     t1 = addTeacher('t001', "Alex", "Alex123")
71     t2 = addTeacher('t002', "Jack", "Jack123")
72     t3 = addTeacher('t003', "Rain", "Rain123")
73     #
74     s1 = addStudent('s001', "chenronghua", "abc123")
75     s2 = addStudent('s002', "niuhanyang", "abc123")
76     s3 = addStudent('s003', "wangsen", "abc123")
77     #
78     b1 = addBatch("python14", "python")
79     b2 = addBatch("pythonS2", "python")
80     b3 = addBatch("Ops10", "Linux")
81 
82     b1.students = [s1, s2, s3]
83     b1.teachers = [t1, t2]
84 
85     for i in b1.students:
86         obj = dbt.Task(date='2016-10-26', teacher_id=t1.id, student_qq=i.qq, batch_name=b1.name)
87         db.add(obj)
88         db.commit()
89     #
90     # obj = db.query(dbt.Teacher).filter(dbt.Teacher.id == "t001").first()
91     # for i in obj.tbatchs:
92     #     if i.name == 'python14':
93     #         for j in i.students:
94     #             if j.qq == 's001':
95     #                 print(j.name, j.password)
96 
97     pass
db handler
原文地址:https://www.cnblogs.com/tntxyz/p/6006948.html