【问题标题】:Using python on Google App Engine to handle HTML form data using POST method在 Google App Engine 上使用 python 使用 POST 方法处理 HTML 表单数据
【发布时间】:2012-10-31 21:42:19
【问题描述】:

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

操作系统:Win 7 x64 蟒蛇 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)

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>

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

【问题讨论】:

    标签: python web-services google-app-engine cgi


    【解决方案1】:

    您不应该使用cgi.FieldStorage。 Webapp2 与所有 Web 框架一样,具有处理 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

    【讨论】:

    • 花了大约 3 个小时试图解决这个问题,感谢您的帮助!
    • 使用 .POST 代替 .get 有什么好处(hus787 的回答)?
    【解决方案2】:

    最好不要把网址像

    “http://localhost:8080”

    如果你使用类似的东西

    action="/"

    它将在本地 Web 服务器 (localhost:8080) 和公共 Web 服务器 (... .appspot.com) 中工作

    【讨论】:

      【解决方案3】:

      你为什么不试试:

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

      Source

      【讨论】:

        【解决方案4】:

        入门指南中有一个使用表单并将结果提交到数据存储区的完整示例:https://developers.google.com/appengine/docs/python/gettingstartedpython27/usingdatastore

        处理 html 输出的更好方法是使用 jinja 2。另请参阅入门指南。 https://developers.google.com/appengine/docs/python/gettingstartedpython27/templates 在此之后看看 WTForms。

        【讨论】:

          猜你喜欢
          • 2012-08-19
          • 1970-01-01
          • 1970-01-01
          • 2013-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多