Miles Miles - 2 months ago 6
Python Question

Flask: differences between request.form["xxxxx"], request.form.get("xxxxxx") and request.args.get("xxxxx")?

What are the differences between

flask.request.form["xxx"]
,
flask.request.form.get("xxx")
and
flask.request.args.get("xxx")
?

I have this question because I am using flask-login to handle authentication.

In particular in the following code (taken from the flask-login github page), I don't understand why with
req.form.get("email")
, email is
None
, while with
req.form["email"]
, email hasn't a value. Here's the code.

@login_manager.request_loader
def request_loader(req):
email = req.form.get('email')
if email not in users:
return

user = User()
user.id = email

# DO NOT ever store passwords in plaintext and always compare password
# hashes using constant-time comparison!
user.is_authenticated = req.form['pw'] == users[email]['pw']

return user

Answer

The proper use-case get() is to return a default value when the key you are looking for doesn't exist in a dictionary.

For example, if you have a dictionary d such that :

d = {'foo': 'bar'}

Doing the following will return None:

d.get('baz', None)

While doing the following will throw an exception:

d['baz']
Comments