Steeven_b
Steeven_b

Reputation: 777

Use Flask view that requires query args outside of request

I have a Flask view that uses request.args to get some query args from the request. I want to call it as a function outside of a request, so request.args won't be available. How can I modify the view function to work independently?

http://localhost:5000/version/perms?arg1=value1&arg2=value2
@app.route(version + 'perms', methods=['GET'])
def get_perms():
    arg1 = request.args.get('arg1')
    arg2 = request.args.get('arg2')

I would like to use this function as a basic Python function, passing it the arguments in the call.

def get_perm(arg1, arg2):

Upvotes: 0

Views: 790

Answers (1)

Juergen Gmeiner
Juergen Gmeiner

Reputation: 225

There is support to get URL parts into python variables, but AFAIK it does not work with query parameters, you need to use request.args for that.

from flask import request
@app.route(version + 'perms', methods=['GET'])
def get_perm():
    arg1 = request.args.get('arg1')
    arg2 = request.args.get('arg2')

If what you want to extract is not a query parameter (i.e. it's not after the ? in the URL), something like this would work (copied straight from the flask documentation - http://flask.pocoo.org/docs/0.11/quickstart/#routing)

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

I am not sure what you mean by "call without the web part" - do you want to call it from other python code, e.g. from a batch job? I guess I would do something like this:

from flask import request
@app.route(version + 'perms', methods=['GET'])
def get_perm_ws():
    arg1 = request.args.get('arg1')
    arg2 = request.args.get('arg2')
    return get_perm(arg1, arg2)

def get_perm(arg1, arg2):
    pass # your implementation here

Another alternative (if you can't put the request parameters somewhere else in the URL) would be a function parameter with default value. Note you really should use something immutable here or you are asking for trouble (a mutable default argument can be modified, and the modified value will be used as default from then on).

@app.route(version + 'perms', methods=['GET'])
def get_perm(params = None):
    if params == None:
        params = request.params
    # your code here

Upvotes: 2

Related Questions