昨日回顾
1.单表查询常用方法有哪些?
2.SQLAlchemy中分页排序如何实现?
3.SQLAlchemy中逻辑运算与聚合如何使用?
4.一对多, 多对多关系如何创建?
5.关系查询如何实现?
6.Flask-SQLAlchemy如何执行自定义SQL语句?
今日内容
-
前后端分离项目的创建 -
学生管理系统案例 — 模型创建与迁移 -
学生管理系统案例 — 增删改查实现 -
前端页面编写与接口测试
1. 前后端分离项目
1.1 项目的创建
project
common
models
settings
utils
__init__.py
project
resources
main.py
__init__.py
vue create myProject
npm install
npm install xxx -s
1.2 跨域配置
Flask跨域配置需要借助flask-cors扩展来实现。
pip install flask-cors
from flask_cors import CORS
CORS(app, supports_credentials=True,
origins=["http://localhost:8080",],
methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["x-requested-with", 'content-type', 'authorization', "author"],
expose_headers="*")
2. 学生管理系统
2.1 介绍与目标实现
stusys
common
models
stu.py
__init__.py
settings
__init__.py
default.py
stusys
resources
stu.py
__init__.py
main.py
manage.py
2.2 模型创建与迁移
- models下的__init__.py中创建db对象
from .stu import Sub, Stu, db
__all__ = ["Sub", "Stu", "db"]
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Sub(db.Model):
__tablename__ = 'sub_tb'
id = db.Column(db.Integer, primary_key=True, doc='专业的ID', autoincrement=True)
name = db.Column(db.String(32), doc='专业名称')
stu_relation = db.relationship('Stu', backref="stu_tb", uselist=False)
class Stu(db.Model):
__tablename__ = 'stu_table'
id = db.Column(db.Integer, primary_key=True, autoincrement=True, doc='学生ID')
name = db.Column(db.String(32), doc='学生姓名')
age = db.Column(db.Integer, doc='学生年龄')
snum = db.Column(db.Integer, unique=True, doc='学生学号')
sub_id = db.Column(db.Integer, db.ForeignKey('sub.id'), doc='专业外键')
- 创建工厂函数: 在stusys下的__init__.py下创建工厂函数
from flask import Flask
from common.models import db
def creat_flask_app(config):
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
return app
- 创建app: 在stusys下的main中创建app
import sys
import os
from flask_cors import CORS
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'common'))
from stusys import creat_flask_app
from common.settings.default import Config
app = creat_flask_app(Config)
if __name__ == '__main__':
CORS(app)
app.run()
- 配置的创建: settings下的default.py
import pymysql
class Config(object):
pymysql.install_as_MySQLdb()
SQLALCHEMY_DATABASE_URI = 'mysql://root:root@127.0.0.1:3306/jiyunstus'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
- 创建迁移脚本
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from common.models.stu import Stu, Sub, db
from stusys.main import app
manage = Manager(app)
migrate = Migrate(app, db)
manage.add_command('db', MigrateCommand)
if __name__ == '__main__':
manage.run()
- 执行迁移命令
python migrate.py db init
python migrate.py db migrate
python migrate.py db upgrade
python manage.py db history
python manage.py shell
python manage.py db current
python manage.py db downgrade xxx版本号
- 创建蓝图 resources > stu.py
from flask import Blueprint
from flask_restful import Api, Resource, marshal
stubp = Blueprint('stubp', __name__)
api = Api(stubp)
class StuResource(Resource):
def get(self):
return 'test'
api.add_resource(StuResource, '/stu', endpoint='stu')
- 注册蓝图与创建api
from flask import Flask
from common.models import db
from flask_restful import Api, Resource
from resources.stu import stubp
def creat_flask_app(config):
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
app.register_blueprint(stubp)
api = Api(app)
return app
- 测试蓝图get请求
postman访问: http://127.0.0.1:5000/stu
响应: "test"
3. 增删改查的实现
3.1 增加学生与专业信息
1. 增加专业与获取专业
from flask import Blueprint
from flask_restful import Api, Resource, marshal
from flask_restful import reqparse
from common.models import Sub, Stu, db
from common.serializers import sub_fields
class SubResource(Resource):
def get(self):
subs = Sub.query.all()
return marshal(subs, sub_fields)
def post(self):
reqps = reqparse.RequestParser()
reqps.add_argument('name')
args = reqps.parse_args()
name = args['name']
sub = Sub(name=name)
try:
db.session.add(sub)
db.session.commit()
except Exception as e:
print(e)
return '专业添加失败'
return '{}-专业添加成功'.format(name)
api.add_resource(SubResorce, '/sub/')
2. 增加学生
class StuResource(Resource):
def post(self):
reqps = RequestParser()
reqps.add_argument('name', type=str)
reqps.add_argument('age', type=int)
reqps.add_argument('snum', type=int)
reqps.add_argument('sub_id', type=int)
args = reqps.parse_args()
stu = Stu(name=args['name'], age=args['age'], snum=args['snum'], sub_id=args['sub_id'])
try:
db.session.add(stu)
db.session.commit()
return '添加成功'
except Exception as e:
print(e)
return '添加失败'
2.3 修改学生信息
def put(self):
reqps.add_argument('id', type=int, required=True)
reqps.add_argument('name', type=str)
reqps.add_argument('age', type=int)
reqps.add_argument('snum', type=int)
reqps.add_argument('sub_id', type=int)
args = reqps.parse_args()
stu_id = args['id']
stu = Stu.query.filter(Stu.id == stu_id)
if stu.all():
stu.update(args)
db.session.commit()
return '更新成功'
else:
return '更新失败'
2.4 查询学生信息
def get(self):
stus = Stu.query.all()
return marshal(stus, stu_fields)
2.5 删除学生
def delete(self):
reqps.add_argument('id', type=int, required=True)
args = reqps.parse_args()
stu_id = args['id']
stu = Stu.query.filter(Stu.id == stu_id)
if stu.all():
stu.delete()
db.session.commit()
return '删除成功'
else:
return '删除失败'
|