I am running the following code; it is from the Twisted Framework’s example list and is of a webserver.
from twisted.web import server, resource
from twisted.internet import reactor
class HelloResource(resource.Resource):
isLeaf = True
numberRequests = 0
def render_GET(self, request):
self.numberRequests += 1
request.setHeader("content-type", "text/plain")
arg = request.args
q = arg['q']
#Added for debugging
for key, value in arg.iteritems():
print key, value
return "I am request #" + str(self.numberRequests) + " " + q[0] + "\n"
reactor.listenTCP(8080, server.Site(HelloResource()))
reactor.run()
To execute:
[user@localhost pytwist]$ python twi.py
Browser URL:
http://localhost:8080/?q=test
However, I am getting the following KeyError Exception on the console:
File "twi.py", line 12, in render_GET
q = arg['q']
exceptions.KeyError: 'q'
Yet, the browser is giving expected output:
I am request #3 test
Also, the console is properly displaying the debug part of the code:
q ['af']
If the output is correct and the key exists properly, then what could be the error? Note that I have tried dict.get() method but the problem persists.
It’s probably because your browser is making two requests. The second request is probably for the
favicon.icofile, and here it doesn’t send theqparameter.Try printing the URL requested.
Related