flask框架会封装一个Request类实例,request类实例对象中包含了关于一次http请求的一切信息。
request类常用属性:
form 记录表单数据 类型:MultiDictargs 记录请求中的查询参数 类型:MultiDictcookies 记录请求中的cookie 类型:dictheaders 记录请求中的报文头method 记录请求中的http方法 类型:stringenviron 记录wsgi服务器转发的环境变量 类型: dicturl 记录请求中的url地址 类型:stringstudent.py __ init__.py
postman API
创建libs utilis.py文件 工具包
可以当做一个公共模块返回数据。 utilis.py
class UTIL: @staticmethod def to_json(status,message,data=None): return { "status":status, "message":message, "data":data }student.py
""" author:liuyongqian date: 2020-10-03 """ from flask import Blueprint, request from model.user import Student from libs.utils import UTIL # import json # # @app.route('/v2/index/<username>', methods=["GET","POST"]) stu_bp = Blueprint("student", __name__, url_prefix="/v1/") #增 /student/add #删 /student/delete #改 /student/modify #查/student/get #用户请求 #/student/get?id=1 #约定俗称的一种规范,不是强制要求 #resutl = { # "status": 1 , #自定义响应状态 # "messages": "xxx", # "data":"返回的数据" 一般定义为list # } @stu_bp.route("/student/get") def get_student(): try: user_id=request.args.get("id",0,int) if user_id!=0: user_info=Student.query.get(user_id) stu_info=user_info.to_json() else: user_info=Student.query.all() stu_info=[stu.to_json() for stu in user_info] # tmp_dict={} # tmp_dict["name"]=user_info.stu_name except: return UTIL.to_json("0","请求失败") return UTIL.to_json("2","请求成功",data=stu_info)结果:
把model对象变成我们所需要的数据结构。 安装 pip install flask-marshmallow
student.py
@stu_bp.route("/student/add", methods = ["POST"]) def add_student(): stu= request.form stu_info = Student(stu["stu_name"], stu["stu_age"], stu["stu_sex"], stu["stu_like"]) db.session.add(stu_info) db.session.commit() return UTIL.to_json("1","添加学生信息成功")结果:
student.py
@stu_bp.route("/student/add", methods = ["POST"]) def add_student(): stu=request.data return stu结果: 传输json格式的数据
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201005220144473.png?x-oss-process=image/watermark,type_ mFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTU1MDUwMA==,size_16,color_FFFFFF,t_70#pic_center)
目录结构 studentApi.py
""" author:liuyongqian date: 2020-10-06 """ from flask import Blueprint,request from model.user import Student from libs.utils import UTIL from flask_restful import Resource,Api from model.user import db api_bp01=Blueprint("api01",__name__,url_prefix="/api") api=Api(api_bp01) class StudentView(Resource): def get(self): try: user_id = request.args.get("id", 0, int) if user_id != 0: user_info = Student.query.get(user_id) stu_info = user_info.to_json() else: user_info = Student.query.all() stu_info = [stu.to_json() for stu in user_info] # tmp_dict={} # tmp_dict["name"]=user_info.stu_name except: return UTIL.to_json("0", "请求失败") return UTIL.to_json("2", "请求成功", data=stu_info) def post(self): stu = request.form stu_info = Student(stu["stu_name"], stu["stu_age"], stu["stu_sex"], stu["stu_like"]) db.session.add(stu_info) db.session.commit() return UTIL.to_json("1", "添加学生信息成功") #设置路由 api.add_resource(StudentView,'/student/')注册蓝图 结果: 添加解析器