0

So I have a flask URL, where there are 2 separate arguments. I want to run the same function with either no arguments, just the first or both. If no specific value is set, I want the unaccounted for arguments to get value None (as opposed to just not existing at all). My current solution involves using 3 @app.route statements, and I was wondering if there was something more efficient i've missed.

@app.route('/URL',defaults={'Arg1':None,'Arg2':None})
@app.route('/URL/<string:Arg1>',defaults={'Arg2':None})
@app.route('/URL/<string:Arg1>/<string:Arg2>')

Thanks!

1
  • I do the same with just one route and using request.args.get('argname') in my handler method but that's just because I didn't know that what you do is even possible Commented Oct 7, 2020 at 17:20

1 Answer 1

1

In that case, just create simple route and access those variables in request.args like so:

@app.route('/test', methods=['GET'])
def test():
    arg1 = request.args.get('arg1', None)
    arg2 = request.args.get('arg2', None)
    if arg1:
        pass  # Do something with it
    elif arg2:
        pass  # Do something with it
    else:
        pass  # do something when no args given
    return jsonify()

And then in url you can pass like this:

/test
or
/test?arg2=321
or
/test?arg1=123
or
/test?arg1=123&arg2=321
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was sure there was something simple I'd missed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.