Skip to main content
 首页 » 编程设计

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

2025年05月04日28zhwl

尝试在 Google App Engine 上开发 Python 网络服务,以处理从 HTML 表单发布的数据。有人可以告诉我我做错了什么吗?所有文件都位于桌面\helloworld 的同一目录中。

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

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) 

页面.html

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

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

请您参考如下方法:

你不应该使用 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"])  

参见 the webapp2 documentation .