Install the extension with easy_install:
$ easy_install Flask-ReqArg
or pip:
$ pip install Flask-ReqArg
You can also download the latest version from GitHub:
$ git clone https://github.com/jason2506/flask-reqarg.git
$ cd flask-reqarg
$ python setup.py develop
When you are writing some web applications, the most common way to fetch the request arguments, such as parameters passed by GET or POST methods, is to fetch values from a dictionary-like object:
from flask import request
@app.route('/foo')
def bar():
arg1 = request.args.get('arg1')
arg2 = request.args.get('arg2')
arg3 = request.args.get('arg3')
# rest of code
The repeatedly calling of request.args.get() is tedious and not interesting for the people who write the code.
Now, Flask-ReqArg can avoid you to write such a boring code.
The simplest way to use it is to put the @request_args decorator on the line before the view function, then use the name of GET or POST arguments as the name of function arguments:
from flask.ext.reqarg import request_args
@app.route('/foo')
@request_args
def bar(arg1, arg2, arg3):
# rest of code
As you can see, the value of request arguments will be automatically bound to the corresponding function arguments. This can make your code simpler and more clear.
For explicitly specifying the request method or argument names to be bound, @request_args also accepts some fetchers as its arguments.
Here is a example:
@request_args(get(), z=post('a'))
def view(x, y, z):
# rest of code
The get() fetcher, which is the first argument of @request_args, binds the first function argument x to the GET argument with the same name. In addition, the post() fetcher binds the function argument z to the POST argument a.
The function argument y, on the other hand, are not explicitly specified in the argument of @request_args. As a result, it is bound to the argument passed by GET or POST method (by default).
Binds request arguments to function arguments.
Parameters: | _source – The default source of the request arguments. Acceptable values include: 'get' (GET method), 'post' (POST method), 'args' (GET or POST method), 'files' (files from POST or PUT method), and 'cookies'. Defaults to 'args'. |
---|
This decorator also accepts some fetchers as arguments. See Using the Fetcher.
Fetches request argument and maps it to the function argument.
Parameters: |
|
---|
Puts the retrieved request arguments in a collection, and then maps it to the function argument.
Parameters: | _storage – A callable which accepts arguments and creates the collection object. Defaults to dict. |
---|
Other acceptable arguments are same as @request_args.