需要两个工具
pip install flask_restful
pip install flask_marshmallow
初始化app:
初始化app的两种方式:
Api(app=app)
或者
api = Api()
api.init__app(app)
from flask_restful import Api
from flask_marshmallow import Marshmallow
api = Api()
ma = Marshmallow()
api.init_app(app)
ma.init__app(app)
显示内容:
views.py文件中:
from flask_restful import Resourse
from utils.function import api
class HelloStudent(Resourse):
显示内容:方式1:
def get(self, id):
stu = Student.query.get(id)
data = {
'name': stu.s_name,
'age': stu.s_age
}
return data
# 显示内容方式2:
首先同级目录下新建StuMarshmallow.py文件:
from utils.function import ma
class StuMarsh(ma.Schema):
class Meta:
fields = ('s_name', 's_age') 定义要 展示的对象的内容
stumarsh = StuMarsh()
from Stu.StuMarshmallow import stumarsh
def get(self, id):
stu = Student.query.get(id)
return stumarsh.jsonify(stu)
def post(self, id):
pass
def patch(self, id):
pass
def put(self, id):
pass
def delete(self, id):
pass
上面定义的是借口访问的方式,postman中不同的请求方式,返回上面对应的不同方法
定义api接口访问的url:
api.add_resourse(HelloStudent, '/api/hello/<int:id>/')
示例: 127.0.0.1:8000/api/hello/3/