使用Google App Engine上的python使用POST方法处理HTML表单数据

use*_*648 1 python google-app-engine cgi web-services

尝试在Google App Engine上开发一个python Web服务,该服务将处理从HTML表单发布的数据.有人可以告诉我我做错了什么吗?所有文件都驻留在桌面\ helloworld上的同一目录中.

操作系统:Win 7 x64 Python 2.7 Google App Engine(本地)

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)
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

使用浏览器(Chrome)查看page.html,我在字段中输入文本并按提交,我希望看到文本显示在浏览器中,但我得到"名称不在表单中".如果我将HTML表单方法更改为get并将python函数更改为def get(self),它可以工作,但我想使用post方法.任何有关解释的帮助将不胜感激.

Dan*_*man 6

你不应该使用cgi.FieldStorage.与所有Web框架一样,Webapp2具有处理POST数据的内置方式:在这种情况下,它通过request.POST.所以你的代码应该只是:

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

请参阅webapp2文档.