Python Forum

Full Version: Dict KeyError in cgi-bin script, works fine via console
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all, I'm experiencing a KeyError when I try to run the following cgi-bin script via my web form. The error indicates the problem resides on line 13 of the script: the key, 'yellow', was not found, even though it's clearly shown in the error message output (it shows the contents of the loaded dict).

#!/usr/bin/env python3.5
import cgi
import cgitb
import pickle
import html

cgitb.enable()
form = cgi.FieldStorage()

print("Content-type: text/html\n\n")

userVars = pickle.load(open("/opt/RampPi/RampPi.CFG", "rb"))
userVars['yellow'] = int(form["yellow"].value)
pickle.dump(userVars, open("/opt/RampPi/RampPi.CFG", "wb"))
text = form["yellow"].value
print("<h1>Save successful</h1>")
print(html.escape(text))
What's interesting is that if I run the exact same commands in the Python3.5 console, it works perfectly:
$ python3.5
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> userVars = pickle.load(open("/opt/RampPi/RampPi.CFG", "rb"))
>>> userVars['yellow']
10
>>> userVars['yellow'] = int(15)
>>> userVars['yellow']
15
>>> userVars['yellow'] = int(10)
>>> userVars['yellow']
10
Permissions on /opt/RampPi/RampPi.CFG are rw-r--r--, and it's owned by the current user (myself). /usr/lib/cgi-bin/ (the location of the script) is owned by root but permissions are rwxr-xr-x. Not sure if that's a factor here but I figure it can't hurt. I would think that if it were a permissions error I would get a different message, but who knows!

I'd appreciate your help. Thanks!
You use 'yellow' as a key twice on that line. Are you sure the error is with userVars and not form?
That could be something... I named the form variable "yellow" as well just because I will have multiple items on the form, and all they do is set the values of corresponding items in the dict, so I wanted to make life easy, so to speak.

Wow, that was dumb...changing the form variable from yellow to yellowIn did it. Thanks!