Flask实现RESTful API

准备工作

首先安装flask_restful三方组件

pip install flask_restful

  在models.py中新建一个类,生成表,往里面插入一些数据。(flask要想使用ORM的话需要安装flask_sqlalchemy三方组件,之前已经说过了,此处不再赘述)

  然后写了一个urls文件,实例化我们的api,把api对象和app绑定,然后__init__.py加入绑定的函数

具体实现

api_urls.py

from flask_restful import Api
from myapp.api import *

api = Api()

def init_api(app):
    api.init_app(app)

api.add_resource(One,'/one')
api.add_resource(Two,'/two')
api.add_resource(Three,'/three/<int:id>')
api.add_resource(Four,'/four/<int:page>/<int:per_page>')
api.add_resource(Five,'/five')
api.add_resource(Six,'/six')
api.add_resource(Seven,'/seven')

__init__.py

from flask import Flask
from myapp.api_urls import init_api
from myapp.ext import init_ext
from myapp.settings import conf


def create_app(env_name):
    app = Flask(__name__)

    app.config.from_object(conf.get(env_name,'debug'))

    init_ext(app)

    init_api(app)
    return app

输出字段与参数解析的不同实现

from flask import request
from flask_restful import Resource, marshal_with, fields, reqparse
from myapp.models import *

#输出字段
#字典套字符串 one_fields
= { 'id':fields.Integer(default=1), #default设置为默认值 'user':fields.String(attribute='name'),       #attribute设置为映射到models中的name字段 'content':fields.String, 'hahaha':fields.String(default='lalala') } class One(Resource): @marshal_with(one_fields) def get(self,*args,**kwargs): id = int(request.args.get('id')) data = News.query.get(id) return data
#字典套列表 two_fields
= { 'id':fields.Integer(default=1), 'name':fields.String(default='wusir'), 'hobby':fields.List(fields.String) } class Two(Resource): @marshal_with(two_fields) def get(self): hobby = ['阅读','运动','敲代码'] return {'hobby':hobby} #字典套字典 three_fields = { 'id': fields.Integer(default=1), 'name': fields.String(default='alex'), 'content':fields.Nested(one_fields) } class Three(Resource): @marshal_with(three_fields) def get(self,id): news = News.query.get(id) return {'content':news}
#字典套列表,列表再套字典 four_fields
= { 'id':fields.Integer(default=1), 'name':fields.String(default='wusir'), 'content':fields.List(fields.Nested(one_fields)) } class Four(Resource): @marshal_with(four_fields) def get(self,page,per_page): news = News.query.paginate(page,per_page,error_out=False) #分页实现 return {'content':news.items}

#参数解析 five_args
= reqparse.RequestParser() five_args.add_argument('id',type=int,required=True,help='id是必填字段,赶紧的填上') #required为True表示是必填字段,help为错误提示信息 five_args.add_argument('name',dest='my_name') #dest表示起别名 five_args.add_argument('hobby',action='append') #action='append'表示字段可以追加写多个 class Five(Resource): def get(self): my_args = five_args.parse_args() print(my_args) print(my_args.get('hobby')) return {'msg':'ok'}
six_args
= reqparse.RequestParser() six_args.add_argument('content',location='form') class Six(Resource): def get(self): my_args = six_args.parse_args() print(my_args) return {'msg':'get'} def post(self): my_args = six_args.parse_args() print(my_args) return {'msg':'post'}
seven_args
= five_args.copy() seven_args.replace_argument('id',type=int,help='随便你填不填',required=True) seven_args.remove_argument('name') seven_args.remove_argument('hobby') class Seven(Resource): def get(self): my_args = seven_args.parse_args() print(my_args) return {'msg':'好了'}

参数解析的位置:

# 从post请求的form里拿参数
parser.add_argument('name', type=int, location='form')

# 从get请求的args里拿参数
parser.add_argument('PageSize', type=int, location='args')

# 从请求头拿参数 headers
parser.add_argument('User-Agent', location='headers')

# 从cookies拿参数
parser.add_argument('session_id', location='cookies')

# 获取文件
parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')

PS:当指定多个解析位置,location 指定为一个列表

文档参考:https://flask-restful.readthedocs.io/en/latest/

posted @ 2018-11-25 19:08  WuSir_ZJ  阅读(675)  评论(0编辑  收藏  举报