Steeven Brunner Steeven Brunner - 4 months ago 36
Python Question

Use Flask Python function without URL

I am writing a webservice in python, I am using Flask library.

@app.route(version + 'perms', methods=['GET'])
def get_perms():


This function takes some arguments, I pass them as below :

localhost:port/version/perms?arg1=value1&arg2=value2


I would like to call this function without using the 'web' part, I mean I would like to use this function as a basic function in python, passing it the arguments in parameters.

Is it a way to do it ? Or I must duplicate the function :

def get_perm(arg1, arg2):

Answer

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
Comments