学习 Flask 扩展 Flask-RESTful

pip install Flask-RESTful

Flask-RESTful扩展。首先,我们来安装上面这个扩展。

 

from flask import Flask
from flask_restful import Api, Resource, reqparse, abort
 
app = Flask(__name__)
api = Api(app)
 
USER_LIST = {
    1: {'name':'Michael'},
    2: {'name':'Tom'},
}
 
parser = reqparse.RequestParser()
parser.add_argument('name', type=str)
 
def abort_if_not_exist(user_id):
    if user_id not in USER_LIST:
        abort(404, message="User {} doesn't exist".format(user_id))
 
class User(Resource):
    def get(self, user_id):
        abort_if_not_exist(user_id)
        return USER_LIST[user_id]
 
    def delete(self, user_id):
        abort_if_not_exist(user_id)
        del USER_LIST[user_id]
        return '', 204
 
    def put(self, user_id):
        args = parser.parse_args(strict=True)
        USER_LIST[user_id] = {'name': args['name']}
        return USER_LIST[user_id], 201
 
class UserList(Resource):
    def get(self):
        return USER_LIST
 
    def post(self):
        args = parser.parse_args(strict=True)
        user_id = int(max(USER_LIST.keys())) + 1
        USER_LIST[user_id] = {'name': args['name']}
        return USER_LIST[user_id], 201
 
api.add_resource(UserList, '/users')
api.add_resource(User, '/users/<int:user_id>')
 
if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)

然后在运行  python new2.py,浏览器打开可以看到:

命令行查看:

 

curl http://127.0.0.1:5000/users

【转自】http://www.cnblogs.com/Erick-L/p/7025708.html

 

posted @ 2018-06-12 11:52  纵一苇之所如-  阅读(240)  评论(0编辑  收藏  举报