39

I'm new to Python and Flask.

I know that I can fetch a GET parameter with request.args.get(varname);. I wanted to check whether a GET request to my server is specifying an optional parameter or not.

Flask documentation didn't help much.

4 Answers 4

58

You can actually use the default value,

opt_param = request.args.get("something")
if opt_param is None:
    print "Argument not provided"
2
  • 1
    @JakobBowyer This is not a claim, and I upvote you answer, but I think for novice in python more immediately useful to show pythonic way ;)
    – Denis
    Commented Jan 9, 2013 at 11:46
  • 4
    What happens if the query parameter has no value? It's a valid query string, and it represents a "flag", not an option. Commented Oct 26, 2018 at 3:06
26

A more Pythonic way to do the same would be using the in operator:

if 'varname' in request.args:
    # parameter 'varname' is specified
    varname = request.args.get('varname')
else:
    # parameter 'varname' is NOT specified
0
9
page = request.args.get("page", 0, type=int)
3

You can check it with this code:

name = request.args.get("name", default=None, type=str)
1
  • 2
    please add some context about your answer.
    – EarlGrey
    Commented Feb 7, 2020 at 20:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.