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.
JavaScript
x
4
1
@app.route('/URL',defaults={'Arg1':None,'Arg2':None})
2
@app.route('/URL/<string:Arg1>',defaults={'Arg2':None})
3
@app.route('/URL/<string:Arg1>/<string:Arg2>')
4
Thanks!
Advertisement
Answer
In that case, just create simple route and access those variables in request.args
like so:
JavaScript
1
12
12
1
@app.route('/test', methods=['GET'])
2
def test():
3
arg1 = request.args.get('arg1', None)
4
arg2 = request.args.get('arg2', None)
5
if arg1:
6
pass # Do something with it
7
elif arg2:
8
pass # Do something with it
9
else:
10
pass # do something when no args given
11
return jsonify()
12
And then in url you can pass like this:
JavaScript
1
8
1
/test
2
or
3
/test?arg2=321
4
or
5
/test?arg1=123
6
or
7
/test?arg1=123&arg2=321
8