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

一曲冷凌霜 提交于 2019-12-22 10:27:04

问题


The get method on user works if the # api.add_resource(User, '/user/') line is uncommented, and the other api.add_resource is. The inverse of that is true to make the post method work.

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)

回答1:


Flask-Restful supports registering multiple URLs for a single resource. Simply provide both URLs when you register the User resource:

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


来源:https://stackoverflow.com/questions/24770999/flask-restful-having-a-get-id-and-post-with-json-in-the-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!