user1347648
user1347648

Reputation: 65

Using python on Google App Engine to handle HTML form data using POST method

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.

Upvotes: 1

Views: 2622

Answers (4)

Eduardo Acero
Eduardo Acero

Reputation: 21

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)

Upvotes: 2

voscausa
voscausa

Reputation: 11706

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.

Upvotes: 0

Bleeding Fingers
Bleeding Fingers

Reputation: 7129

Why don't you try:

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

Source

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600041

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.

Upvotes: 6

Related Questions