day05 flask的建表和增删相关操作

app/models.py

"""_drh_"""
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Grade(db.Model):
    #自增的主键id
    id = db.Column(db.Integer, primary_key=True, autoincrement= True)
    # 定义不能为空,且唯一的班级名称字段
    g_name = db.Column(db.String(10), nullable = False, unique = True)

    stus = db.relationship('Student', backref = 'p')



class Student(db.Model):
   #定义id主键,自增字段
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    #定义不能为空,且唯一的姓名字段
    s_name = db.Column(db.String(10), unique=True, nullable=False)
   #定义整型,默认为20的年龄字段
    age = db.Column(db.Integer, default=20)
   #定义关联表id的外键g_id
    g_id = db.Column(db.Integer, db.ForeignKey('grade.id'),nullable = True)

    __tablename__='stu'

    def save(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commite()

c_s = db.Table('c_s',
               db.Column('s_id', db.Integer, db.ForeignKey('stu.id')),
               db.Column('c_id', db.Integer, db.ForeignKey('course.id'))
               )

class Course(db.Model):
    #自增的主键id
    id = db.Column(db.Integer, primary_key=True, autoincrement= True)
    # 定义不能为空,且唯一的班级名称字段
    c_name = db.Column(db.String(10), nullable = False, unique = True)
    stus = db.relationship('Student', secondary = c_s, backref = 'cou')

app/view.py

"""_drh_"""
from flask import Blueprint
from sqlalchemy import and_

from app.models import db, Student, Grade, Course

blue = Blueprint('app',__name__)

@blue.route('/')
def hello():
    return 'hello1'

@blue.route('/create_db/')
def create_db():
    db.create_all()
    #删除表
    #db.drop_all()
    return '创建表成功'


@blue.route('/add_stu/')
def add_stu():
    #新值学生数据
    stu = Student()
    stu.s_name = '小明'
    stu.age = 20
    db.session.add(stu)
    db.session.commit()
    return '提交成功'

@blue.route('/add_stus/')
def add_stus():
    stu_list=[]
    for i in range(10):
        stu = Student()
        stu.s_name = 'xiaohpng' +str(i)
        stu.age = int(i)
        stu_list.append(stu)
        #db.session.add(stu)
    db.session.add_all(stu_list)
    db.session.commit()
    return '批量插入成功'

@blue.route('/sel_stu/')
def sel_stu():
    #select * from stu where s_name='xiaopng0'
    stu=Student.query.filter_by(s_name='xiaohpng0').first()
    print(stu.s_name)
    print(stu.age)

    return '查询数据成功!'

@blue.route('/del_stu/')
def del_stu():
    #删除年龄0的信息
    stus = Student.query.filter_by(age=0).all()
    for stu in stus:
        db.session.delete(stu)
    
    db.session.commit()
    
    return '删除成功!'

@blue.route('/update_stu/')
def update_stu():
    #获取对象
    stu = Student.query.filter_by(s_name='xiaopng1').first()
    stu.age = 100
    stu.s_name = 'xiaohong'

    #db.session.add(me)  可以不写
    #db.session.commit()
    stu.save()
    return '修改成功!'
@blue.route('/sel_stus/')
def sel_stus():

    stu = Student.query.filter(Student.s_name == 'xiaohpng1').first()
    print(stu)

#查询所有学生信息
    #all()结果为列表,列表中的元素为查询的学生对象
    stus = Student.query.all()
    print(stus)
    stu = Student.query.filter(Student.id == '1').first()



    print(stu)
    #排序 order_by
    stus = Student.query.order_by(-Student.id).all() #降序
    stus = Student.query.order_by(Student.id).all() #升序

    print(stus)
    #offset limit
    stus = Student.query.limit(3).all()
    page = 1
    stus = Student.query.offset((page-1)*3).limit(2).all()

    #大于gt  小于lt
    #大于等于ge   小于等于le
    stus = Student.query.filter(Student.age.__ge__(10)).all()

    #where id in [1,2,3,4]
    stus = Student.query.filter(Student.id.in_([1,2,3,4])).all()
    stus = Student.query.filter(Student.age >= 10).all()
    print(stu)
    stu = Student.query.filter(Student.age==2,
                               Student.s_name.like('xiao%')).all()   #多条件查询

    stu = Student.query.filter(Student.age == 2 or
                               Student.s_name.like('xiao%')).all()

    # and 或者 or

    return '查询学生信息'


#5day

@blue.route('/add_grade/')
def add_grade():
    grades_name = ['Python', 'Jave','VHDL','C++']
    for name in grades_name:
        g = Grade()
        g.g_name = name
        db.session.add(g)
    db.session.commit()
    return '新增班级成功!'

@blue.route('/add_stu_grade/')
def add_stu_grade():
    #给学生分配班级
    stus = Student.query.filter(Student.id.in_([1,5,6])).all()
    for stu in stus:
        #分配给python班
        stu.g_id = 1
        stu.save()
    return '分配班级成功!'

@blue.route('/sel_stu_by_grade/')
def sel_stu_grade():
    # 通过班级查询学生的信息
    g = Grade.query.filter(Grade.g_name == 'Python').first()
    print (g.stus)
    stu_names = [stu.s_name for stu in g.stus ]
    print(stu_names)
    return '通过班级查询学生成功!'


@blue.route('/sel_grade_by_stu/')
def sel_grade_by_stu():
    stu = Student.query.filter(Student.s_name == 'xiaohpng0').first()
    print (stu.g_id)
    #g = Grade.query.get(stu.g_id)
    print (stu.p)


    return '通过学生查询班级成功!'

@blue.route('/add_cou/')
def add_cou():
    course_names = ['物理', '高数', '英语']
    for name in course_names:
        cou = Course()
        cou.c_name = name
        db.session.add(cou)
    db.session.commit()
    return '创建课程表成功!'

@blue.route('/add_cou_to_stu/')
def add_cou_to_stu():
    # 学生添加课程
    # 给id = 1的学生添加线代高数课程
    stu = Student.query.get(1)
    print(stu.cou)
    cou1 = Course.query.filter(Course.c_name == '物理').first()
    cou2 = Course.query.filter(Course.c_name == '高数').first()
    # stu.cou 返回的值为学生选择的课程对象组成的列表结果
    stu.cou.append(cou1)
    stu.cou.append(cou2)
    # 提交
    db.session.commit()

    return '学生添加课程成功!'

@blue.route('/del_stu_cou/')
def del_stu_cou():
    stu = Student.query.get(1)
    cou2 = Course.query.filter(Course.c_name == '高数').first()
    #删除remove
    stu.cou.remove(cou2)
    db.session.commit()
    return '删除课程成功!'

manage.py


from flask import Flask
from flask_script import Manager
from app.models import db
from app.views import blue

app = Flask(__name__)

app.register_blueprint(blueprint=blue)



app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/flask9'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

manage = Manager(app)
if __name__ == '__main__':
    manage.run()

你可能感兴趣的:(day05 flask的建表和增删相关操作)