简体   繁体   English

flask-restful有一个get / <id>并在同一个类中使用json发布

[英]flask-restful having a get/<id> and post with json in the same class

The get method on user works if the # api.add_resource(User, '/user/') line is uncommented, and the other api.add_resource is. 如果#api.add_resource(User,'/ user /')行被取消注释,而另一个api.add_resource是,则用户的get方法有效。 The inverse of that is true to make the post method work. 相反的是使post方法有效。

How can I get both of these paths to work? 如何让这两条路径都能正常工作?

from flask import Flask, request
from flask.ext.restful import reqparse, abort, Api, Resource
import os
# set the project root directory as the static folder, you can set others.
app = Flask(__name__)
api = Api(app)

class User(Resource):

    def get(self, userid):
        print type(userid)
        if(userid == '1'):
            return {'id':1, 'name':'foo'}
        else:
            abort(404, message="user not found")

    def post(self):
        # should just return the json that was posted to it
        return request.get_json(force=True)

api.add_resource(User, '/user/')
# api.add_resource(User, '/user/<string:userid>')

if __name__ == "__main__":
    app.run(debug=True)

Flask-Restful supports registering multiple URLs for a single resource . Flask-Restful 支持为单个资源注册多个URL Simply provide both URLs when you register the User resource: 注册User资源时,只需提供两个URL:

api.add_resource(User, '/user/', '/user/<userid>')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM