Created
June 6, 2018 13:53
-
-
Save uMtMu/be0682823140e2b1418d6795203477e0 to your computer and use it in GitHub Desktop.
Flask-webargs both url path parameter and query parameter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask.views import MethodView | |
from webargs import fields | |
from webargs.flaskparser import use_args | |
app = Flask(__name__) | |
class Task(MethodView): | |
@use_args({'id': fields.Str(location='view_args'), 'name': fields.Str()}) | |
def get(self, args): | |
return 'Hello {} {}'.format(args['id'], args['name']) | |
task_view = Task.as_view('task_api') | |
app.add_url_rule( | |
'/task/<id>', | |
view_func=task_view, | |
methods=['GET']) | |
if __name__ == '__main__': | |
app.run(debug=True) | |
# http://localhost:5000/task/12?name=mysql | |
# TypeError: get() got an unexpected keyword argument 'id' | |
# But this works | |
from flask import Flask | |
from flask.views import MethodView | |
from webargs import fields | |
from webargs.flaskparser import use_args | |
app = Flask(__name__) | |
@app.route('/task/<id>/') | |
@use_args({'id': fields.Str(location='view_args'), 'name': fields.Str()}) | |
def greeting(args, **kwargs): | |
return 'Hello {} {}'.format(args['id'], args['name']) | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment