CGI with Python
Question: I'm beginning to use CGI with Python.

After running the following piece of code:

    
    
    #!c:\python34\python.exe
    
    import cgi
    
    
    print("Content-type: text/html\n\n") #important
    
    
    def getData():
        formData = cgi.FieldStorage()
        InputUN = formData.getvalue('username')
        InputPC = formData.getvalue('passcode')
        TF = open("TempFile.txt", "w")
        TF.write(InputUN)
        TF.write(InputPC)
        TF.close()
    
    if __name__ =="__main__":
        LoginInput = getData()
        print("cgi worked")
    

The following error occurs:

    
    
    Traceback (most recent call last):
      File "C:\xampp\htdocs\actual\loginvalues.cgi", line 21, in <module>
        LoginInput = getData()
      File "C:\xampp\htdocs\actual\loginvalues.cgi", line 16, in getData
        TF.write(InputUN)
    TypeError: must be str, not None
    >>> 
    

I'm trying to write the values, inputted in html, to a text file.

Any help would be appreciated :)


Answer: Your calls to `getValue()` are returning `None`, meaning the form either
didn't contain them, had them set to an empty string, or had them set by name
only. Python's CGI module ignores inputs that aren't set to a non-null string.

Works for Python CGI:

  * `mysite.com/loginvalues.cgi?username=myname&pass=mypass`

Doesn't work for Python CGI:

  * `mysite.com/loginvalues.cgi?username=&pass=` (null value(s))
  * `mysite.com/loginvalues.cgi?username&pass` (Python requires the `=` part.)

To account for this, introduce a default value for when a form element is
missing, or handle the None case manually:

    
    
    TF.write('anonymous' if InputUN is None else InputUN)
    TF.write('password' if InputPC is None else InputUN)
    

As a note, passwords and other private login credentials should never be used
in a URL. **URLs are not encrypted**. Even in HTTPS, the URL is sent in plain
text that anyone on the network(s) between you and your users can read.

The only time a URL is ever encrypted is over a tunneled SSH port or an
encrypted VPN, but you can't control that, so never bank on it.

