Python Forum
why is user = form.getfirst("user", "").upper() safe? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: why is user = form.getfirst("user", "").upper() safe? (/thread-14288.html)



why is user = form.getfirst("user", "").upper() safe? - shanepy - Nov-22-2018

Hello,

https://docs.python.org/3.5/library/cgi.html#higher-level-interface

import cgi
form = cgi.FieldStorage()
user = form.getfirst("user", "").upper()    # This way it's safe.
...
Why does converting to the cgi form data to upper case make it "safe"?


RE: why is user = form.getfirst("user", "").upper() safe? - micseydel - Nov-24-2018

My best guess is that the default argument, the empty string, prevents None being returned, which would result in the upper call throwing a AttributeError. The upper call doesn't make it safe, it's what's being made safe.


RE: why is user = form.getfirst("user", "").upper() safe? - buran - Nov-26-2018

It's not converting to upper() that makes it safe but using getfirst() method instead of getvalue(). i.e. if user supply list, instead of single value.
Note that upper() is present also in the original example of code that would fail.


RE: why is user = form.getfirst("user", "").upper() safe? - shanepy - Nov-27-2018

@buran: that makes more sense, but I don't see what use upper() serves in this example since
form.getfirst("user", "")
could only return a string.


RE: why is user = form.getfirst("user", "").upper() safe? - buran - Nov-27-2018

upper() is not meant to convert user input to str. It's meant to convert any str to uppercase string. That is why the initial example would fail if user supply list instead of str.

>>> 'Some StrinG'.upper()
'SOME STRING'
>>>



RE: why is user = form.getfirst("user", "").upper() safe? - shanepy - Nov-27-2018

I understand the upper() method is used to trigger an AttributeError exception in case it is called on a list but that could not possibly happen in the example code-
user = form.getfirst("user", "").upper()    # This way it's safe.
so why call it?


RE: why is user = form.getfirst("user", "").upper() safe? - buran - Nov-27-2018

No, this is the solution, not the example code for error.
The example code for error is this one:
user = form.getvalue("user").upper()
now, if form.getvalue("user") returns list and you call upper() on it you will get an error.
as explained in the docs, you can test for what is returned. but there is alternative - if instead you use
user = form.getfirst("user", "").upper()
it will return just the first element (single string) or "" and upper() will not raise exception

you can also use form.getlist() in which case you will always get a list. In any case the code is more compact and clean compared to the one if you check what is returned.