在Google App Engine中使用Python处理表单提交后的显示

1 投票
3 回答
1146 浏览
提问于 2025-04-16 14:07

在提交表单后,页面内容没有显示,但直接访问页面时却能看到。我有一段Python App Engine的代码,试图跳转到一个新页面,并显示一段在代码中定义的文本(也就是说,这段文本不是写在HTML里的)。但是,当我点击表单的提交按钮时,页面却是空白的,没有任何错误信息。

我一直在使用Google App Engine的代码示例。这个表单只是用来选择一些选项,但我其实并没有从中收集任何数据,应该是直接跳转到新页面的,但它没有跳转,我也找不到问题出在哪里。

我有

class MainPage(webapp.RequestHandler):
    def get(self):

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

还有

class Confirm(webapp.RequestHandler):
    def post(self):
       self.response.headers['Content-Type'] = 'text/plain'
       self.response.out.write('You have confirmed!')



application = webapp.WSGIApplication(
                                 [('/', MainPage),
                                  ('/confirm', Confirm)],
                                 debug=True)

def main():
   run_wsgi_app(application)

if __name__ == "__main__":
   main()

以及在HTML文件:index.html

<html>
        <body>
          <form action="/confirm" method="post">
            <div><textarea name="content" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Submit"></div>
          </form>
        </body>
      </html>

我想知道,为什么当我提交表单时,收不到“你已确认!”的消息,而直接访问/confirm时却能看到。谢谢。

3 个回答

0

我会用curl来测试你说的POST请求到Confirm是否正常工作,试着发点东西:

curl -v0 -F content=blah -F submit=submit 'http://my-app.appspot.com/confirm'

如果这样没问题,那我会用HttpFox(一个Firefox的扩展)来查看发送到服务器的数据。

看起来你可能没有提交你认为的内容,或者你的POST处理程序没有按你想的那样工作。以上两个步骤应该能帮助你搞清楚到底是哪种情况。

0

@Rusty,我觉得你应该把表单提交的方法改成GET或者POST,并确保在application.py里也写的是一样的。或者你可以试试这样做:

class Confirm(webapp.RequestHandler):
    def post(self):    
       self.response.headers['Content-Type'] = 'text/plain'
       self.response.out.write('You have confirmed!')
    def get(self):
       return Confirm.post(self)
1

你的代码运行得很顺利;可能是因为你在实现 post 方法时出现了奇怪的缩进错误(这可能就是导致405错误的原因)。

把我的 application.py 复制粘贴一下,然后再试试:

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, {}))

class Confirm(webapp.RequestHandler):
    def post(self):    
       self.response.headers['Content-Type'] = 'text/plain'
       self.response.out.write('You have confirmed!')

application = webapp.WSGIApplication(
                                 [('/', MainPage),
                                  ('/confirm', Confirm)],
                                 debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

撰写回答