1.配置views文件 apps/views
from flask import Blueprint, render_template, redirect, \
url_for, request
from app.models import db
blue = Blueprint('app', __name__)
@blue.route('/index/', methods=['GET'])
def index():
if request.method == 'GET':
return render_template('back/index.html')
# 传入数据并渲染index页面
@blue.route('/index1/', methods=['GET'])
def index1():
if request.method == 'GET':
data = ['Python', 'Vue', 'Linux', 'Celery', 'RabbitMQ',
'MySQL', 'MongoDB', 'Redis', 'Scrapy', 'Urllib',
'Requests', 'Selenium', 'Django',
'Flask', 'Tornado', 'Sanic']
content_h2 = 'H2标签
'
return render_template('back/index1.html',
data=data,
content_h2=content_h2)
# return render_template('web/index.html')
# 创建学生对象表
@blue.route('/create_db/', methods=['GET'])
def create_db():
# 创建所有模型对应的表
db.create_all()
# 删除所有模型对应的表
# db.drop_all()
return '创建表成功'
2.模型文件 app/models
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
# 生成对象,ORM
db = SQLAlchemy()
1.一对多模型建立
class Grade(db.Model):
id = db.Column(db.Integer, primary_key=True)
g_name = db.Column(db.String(50))
stus = db.relationship('Student', backref='g')
# 建立外键联系,设置返回g,提供反向引用声明
__tablename__ = 'grade'
2.多对多模型建立
# 中间表course_student
# 两个外键列c_id,s_id
c_s = db.Table('c_s',
db.Column('c_id', db.Integer, db.ForeignKey('course.id')),
db.Column('s_id', db.Integer, db.ForeignKey('stu.id'))
)
class Course(db.Model):
id = db.Column(db.Integer, primary_key=True)
c_name = db.Column(db.String(50), unique=True)
# 多对多的关联关系可以写在任何一方,反向引用c当使用course查询时.stus,当使用student查询时.c
stus = db.relationship('Student', secondary=c_s, backref='c')
__tablename__ = 'course'
# 定义模型
class Student(db.Model):
# 自增的int类型的主键,长度11位
id = db.Column(db.Integer, primary_key=True)
# 长度50,且唯一,且不能为空的s_name字段
s_name = db.Column(db.String(50), unique=True, nullable=False)
# 默认为20的s_age字段
s_age = db.Column(db.Integer, default=20)
# 默认为当前时间的create_time字段
# django中默认创建时间: auto_now_add=True,
# 修改时间:auto_now=True
create_time = db.Column(db.DateTime, default=datetime.now())
# 外键字段
s_g = db.Column(db.Integer, db.ForeignKey('grade.id'), nullable=True)
# 定义表名
__tablename__ = 'stu'
# def __str__(self):
def __repr__(self):
return ''.format(self.id)
def save(self):
# 创建 、修改
db.session.add(self)
db.session.commit()
# def __init__(self, name):
#
# self.s_name=name
#
# def __new__(cls, *args, **kwargs):
#
# pass
#
# def __del__(self):
# # 析构函数,当对象引用计数为0时,被回收
# pass
- app/stu_views 学生视图函数文件
stu_blue = Blueprint('stu', __name__)
1.创建蓝图
2.注册路由
@stu_blue.route('/stu/', methods=['GET', 'POST', 'DELETE', 'PATCH'])
def stu():
if request.method == 'GET':
3.# 名字查询
stu = Student.query.filter(Student.s_name == 'vincent').first()
print(stu)
# Django的ORM中,get(条件),如果条件不成立结果报错,如果条件对应多个结果则报错
# Flask中,get(主键值),查询的是主键所对应的数据,查询不到返回None
4. get根据主键查询
stu = Student.query.get(20)
print(stu)
5. # 排序
# order_by()
# 升序order_by(Student.id)
# 降序order_by(-Student.id)
stus = Student.query.order_by(-Student.id).all()
print(stus)
6.分页
# offset、limit
# offset偏移:跳过几个元素
# limit: 截图几个元素
# django中Paginator()用于分页
page = 3
stus = Student.query.offset((page - 1)*2).limit(2).all()
print(stus)
paginate(page, per_page, error_out=True)
# page 当前页数
# per_page 每页显示的条数
stus = Student.query.paginate(1, 2)
print(stus.items)
# 是否有上一页: flask中has_prev django中has_previous
# 是否有下一页: flask中has_next django中has_next
# 下一页角码: flask中next_num django中next_page_number
# 上一页角码: flask中prev_num django中previous_page_number
7.# 模糊查询,icontains,and_、not_、or_,startswith, endswith, like
# contains like '%三%'
stus = Student.query.filter(Student.s_name.contains('三')).all()
stus = Student.query.filter(Student.s_name.like('%三%')).all()
print(stus)
# startswith like '三%'
stus = Student.query.filter(Student.s_name.startswith('三')).all()
stus = Student.query.filter(Student.s_name.like('三%')).all()
print(stus)
# endswith like '%三'
stus = Student.query.filter(Student.s_name.endswith('三')).all()
stus = Student.query.filter(Student.s_name.like('%三')).all()
print(stus)
# like % _
stus = Student.query.filter(Student.s_name.like('_三')).all()
print(stus)
# 与或非,django: 且
# filter(条件1,条件2,条件3) filter(Q(条件1),Q(条件2),Q(条件3))
# django :或
# filter(Q(条件1) | Q(条件2) | Q(条件3))
# django :非
# filter(~Q(条件1),Q(条件2),Q(条件3))
8.# 与或非,flask,and_,or_,not_
# 且操作, and_
stu = Student.query.filter(Student.s_name.like('%三%'))\
.filter(Student.s_age == 20).all()
stu = Student.query.filter(Student.s_name.like('%三%'),
Student.s_age == 20).all()
stu = Student.query.filter(and_(Student.s_name.like('%三%'),
Student.s_age == 20)).all()
# 或操作,or_
stus = Student.query.filter(or_(Student.s_name.like('%三%'),
Student.s_age == 20)).all()
# 非操作,not_
stus = Student.query.filter(not_(Student.s_name.like('%三%')),
Student.s_age == 20).all()
print(stus)
# django中: gt gte lt lte
9.# flask中: gt ge lt le > >= < <= ==
stus = Student.query.filter(Student.s_age.__gt__(20)).all()
stus = Student.query.filter(Student.s_age >= 20).all()
print(stus)
10.# in_ notin_
stus = Student.query.filter(Student.id.in_([1, 2, 3])).all()
stus = Student.query.filter(Student.id.notin_([1, 2, 3])).all()
print(stus)
return '查询学生信息成功'
11.# 增操作
if request.method == 'POST':
# 创建一个学生对象信息
# 创建学生信息
# student = Student()
# student.s_name = 'admin'
# # add()方法只是在准备向数据库中插入数据
# db.session.add(student)
# # commit()事务提交,将数据插入到数据库中
# db.session.commit()
# 创建多个学生对象信息
names = ['张三', 'coco', 'vincent', '李四']
stus = []
for name in names:
student = Student()
student.s_name = name
stus.append(student)
db.session.add_all(stus)
db.session.commit()
return '创建学生信息成功'
12.#删除对象
if request.method == 'DELETE':
# Django中all()查询结果为QuerySet,取第一个元素all().first()
# Flask中all()查询结果为list,取第一个元素all()[0]
stus = Student.query.filter(Student.s_name == 'coco').all()
stu = Student.query.filter(Student.s_name == 'coco').first()
print(stu)
stu = Student.query.filter_by(s_name='coco').first()
print(stu)
# delete()删除,接收删除的对象
db.session.delete(stu)
db.session.commit()
return '删除学生信息成功'
13.# 修改数据也使用add
if request.method == 'PATCH':
stu = Student.query.filter(Student.s_name == '李四').first()
stu.s_age = 33
stu.s_name = '小李'
# 修改数据,add(修改对象)这句话可写可不写
# db.session.add(stu)
# db.session.commit()
stu.save()
return '修改学生信息成功'
14. # 修改数据
@stu_blue.route('/stu_grade/', methods=['GET'])
def stu_grade():
# 将id为1,2,3的学生分配到微电子学
stus = Student.query.filter(Student.id.in_([1,2,3])).all()
for stu in stus:
stu.s_g = 2
stu.save()
return '学生分配班级成功'
15. # 一对多的查询使用
@stu_blue.route('/sel_stu_grade/', methods=['GET'])
def sel_stu_grade():
# 通过班级查询学生内容,一查多
grade = Grade.query.filter(Grade.g_name == '微电子学').first()
stus = grade.stus
# 通过学生查询班级,多查一
stu = Student.query.filter(Student.s_name == 'admin').first()
grade = stu.g
return '查询成功'
16. #
@stu_blue.route('/sel_stu_course/', methods=['GET'])
def sel_stu_course():
# 向中间表加信息
cou1 = Course.query.filter(Course.c_name == 'VHDL').first()
cou2 = Course.query.filter(Course.c_name == 'JAVA').first()
stus = Student.query.filter(Student.id.in_([1,2])).all()
# 获取课程所关联的学生信息
# print(cou1.stus)
# for stu in stus:
# cou1.stus.append(stu)
# print(cou1.stus)
# 向中间表加数据,append,向中间表删除数据,remove
for stu in stus:
# stu.c.append(cou2)
stu.c.remove(cou2)
db.session.commit()
return '学生和课程'
4.templates/index.html 模板文件
{% block css %}
{{ super() }}
{# 在django中模板语法: {% block.super %} #}
{# django中加载样式:{% load static %} {% static 'css/other.css' %} #}
{% endblock %}
{# 标签: for、if、{% 标签 %} {% end标签 %} #}
{# {{ 变量 }}: 解析变量的值 #}
{{ data }}
{% for item in data %}
{% if item == 'Vue' %}
{{ item }}
{% else %}
{{ item }}
{% endif %}
{% endfor %}
{# flask中获取data中第二个元素 #}
{# django中获取data中第二个元素, data.1 #}
{{ data[1] }}
{{ content_h2 }}
{# 过滤器,使用管道符'|' ,safe加载样式 striptags删除格式#}
{{ content_h2 | safe }}
{{ content_h2 | striptags }}
{{ content_h2 | length }}
5.manage 管理文件
app = Flask(__name__)
app.register_blueprint(blueprint=blue)
app.register_blueprint(blueprint=stu_blue,url_prefix='/stu')
# 数据库的配置
# mysql+pymysql://root:password@host:port/1902flask
# mysql+pymysql://root:@127.0.0.1:3306/1902flask
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/1902flask'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
# 初始化方法,在views文件中创建db对象时,未传入app,则需调用init_app方法对app进行初始化
if __name__ == '__main__':
manage = Manager(app)
manage.run()