Reputation: 1530
I can access /v1/folder
but cannot access /v1/folder/<folder-id>
. Could you tell me the reason? In the flask-request document said add_resource()
can route multiple URI. But I cannot. Maybe I misunderstand something. Please tell me if you find the clue.
from flask import request
from flask_restful import Resource, abort
class Folder(Resource):
def post(self, folder_id):
return { "message":"post with folder_id"}, 200
def post(self):
return { "message":"post without folder_id"}, 201
app = Flask(__name__)
.....
api_bp = Blueprint('api', __name__)
api = Api(api_bp, serve_challenge_on_401=True)
api.add_resource( Folder, '/v1/folder', '/v1/folder/<string:folder_id>')
app.register_blueprint(api_bp)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True )
The error messages is "TypeError: post() got an unexpected keyword argument 'folder_id' ". What's wrong?
Upvotes: 1
Views: 1630
Reputation: 2243
Python does not support function/method overloading, so the post
method you declared last is always going to be the one that's used. Instead, you should use the tools Python does provide - default values for arguments.
I would personally do the following:
from flask import request
from flask_restful import Resource, abort
class Folder(Resource):
def post(self, folder_id=None):
if folder_id is None:
return self.__simple_post()
else:
return self.__parameter_post(folder_id)
def __parameter_post(self, folder_id):
return { "message":"post with folder_id"}, 200
def __simple_post(self):
return { "message":"post without folder_id"}, 201
app = Flask(__name__)
.....
api_bp = Blueprint('api', __name__)
api = Api(api_bp, serve_challenge_on_401=True)
api.add_resource( Folder, '/v1/folder', '/v1/folder/<string:folder_id>')
app.register_blueprint(api_bp)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True )
Or you could handle the logic in the post
method, if the logic is similar enough and not too long. If the logic ends up being unreadable, though, consider using the approach I suggested.
Upvotes: 2