1

Attempting to develop a python web service on the Google App Engine that will handle data posted from an HTML form. Can someone please advise what I'm doing wrong? All files residing in the same directory on the desktop \helloworld.

OS: Win 7 x64 Python 2.7 Google App Engine (Local)

helloworld.py

import webapp2
import logging
import cgi

class MainPage(webapp2.RequestHandler):

  def post(self):
    self.response.headers['Content-Type'] = 'text/plain'
    form = cgi.FieldStorage()
    if "name" not in form:
      self.response.write('Name not in form')
    else:
      self.response.write(form["name"].value)

app = webapp2.WSGIApplication([('/', MainPage)],debug=False)

page.html

<html>
<body>
  <form action="http://localhost:8080" method="post">
    Name: <input type="text" name="name"/>
    <input type="submit" value="Submit"/>
  </form>
</body>
</html>

Using a browser (Chrome) viewing the page.html, I input a text into the field and press submit, I expect to see the text being displayed in the browser, but I get "Name not in form". It works if I change the HTML form method to get and the python function to def get(self), but I would like to use the post method. Any help with explanation would be appreciated.

4 Answers 4

6

You shouldn't be using cgi.FieldStorage. Webapp2, like all web frameworks, has a built-in way of handling POST data: in this case, it's through request.POST. So your code should just be:

if "name" not in self.request.POST:
    self.response.write('Name not in form')
else:
    self.response.write(self.request.POST["name"]) 

See the webapp2 documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Spent around 3 hours trying to figure this out, thanks for the help!
Is there a benefit of using .POST instead of .get (hus787's answer)?
2

Better do not put URL like

"http://localhost:8080"

If you use something like

action="/"

it will work in the local web server (localhost:8080) and also in the public web server (... .appspot.com)

Comments

0

Why don't you try:

name = self.request.get('name')

Source

Comments

0

There is a complete example using forms and submitting the results to the datastore in the get started guide: https://developers.google.com/appengine/docs/python/gettingstartedpython27/usingdatastore

A better way to handle html output, is using jinja 2. See also the getting started guide. https://developers.google.com/appengine/docs/python/gettingstartedpython27/templates After this have a look at WTForms.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.