rainu
rainu

Reputation: 763

NameError: global name 'q' is not defined

I was able run the Hello World program in the google app engine in below link https://cloud.google.com/appengine/docs/python/

But after I have modified the code for the main.py file (Trying out new handler) I am getting the below error.

Traceback (most recent call last):
  File "/home/natesan/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "/home/natesan/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/home/natesan/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/home/natesan/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/home/natesan/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/home/natesan/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/home/natesan/webapps/udacity1/main.py", line 29, in get
    self.request.get(q)
NameError: global name 'q' is not defined

The main.py file is as below.

import webapp2

form="""
<form action="/Testform">
    <input name="q" >
    <input type="submit">
</form>
"""
class TestHandler(webapp2.RequestHandler):
    def get(self):
        self.request.get(q)
        self.response.write(q)

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write(form) 

app = webapp2.WSGIApplication([
    ('/', MainHandler),('/Testform',TestHandler)
], debug=True)

Can anyone please help me out what the error is.

Upvotes: 0

Views: 1593

Answers (1)

Muhammad Ali
Muhammad Ali

Reputation: 340

You need to write q in quotes like this: "q".

Without quotes, q will be treated as a variable and since you haven't declared it, the error is raised.

I modified the TestHandler class as below.

class TestHandler(webapp2.RequestHandler):
    def get(self):
        q=self.request.get("q")
        self.response.write(q)

Assign a value to the variable q=self.request.get("q") and display it in the browser with self.response.write(q)

Upvotes: 4

Related Questions