Flask-Restful
1.安装
pip install Flask-Restful
2.注册组件
from flask_restful import Api
rest_api=Api()
rest_api.init_app(app)
3.GET/POST/PUT/DELETE请求
from flask_restful import Resource
class PostApi(Resource):
def get(self):
pass
def post(self):
pass
def put(self):
pass
def delete(self):
pass
4.注册路由
rest_api.add_resource(PostApi,
'/api/post',
'/api/post/',
endpoint='api'
)
5.格式化输出
from flask_retful import fields,marshal_with
post_fields={
'title':fields.String(),
'text':fields.String(),
'publish_date':fields.DateTime()
}
class PostApi(Resource):
@marshal_with(post_fields)
def get(self,post_id=None):
if post_id:
print(post_id)
post=Post.objects(id=post_id).get_or_404()
return post
else:
args=post_get_parser.parse_args()
page=args['page'] or 1
posts=Post.objects.paginate(page=page,per_page=10).items
return posts
6.请求参数获取与限制
from flask_retful import reqparse
post_get_parser=reqparse.RequestParser()
post_get_parser.add_argument(
'page',
type=int,
location=['args','headers'],
required=False,
help='page out of index'
)
class PostApi(Resource):
@marshal_with(post_fields)
def get(self,post_id=None):
if post_id:
print(post_id)
post=Post.objects(id=post_id).get_or_404()
return post
else:
args=post_get_parser.parse_args()
page=args['page'] or 1
posts=Post.objects.paginate(page=page,per_page=10).items
return posts