Google App Engine 入门 :处理表单数据
May 7th, 2008
如果我们希望能显示用户自己的留言,就需要用户通过web表单提交一些信息,然后GAE程序对它们进行处理。Webapp框架使得实现这个过程相当简单。
使用webapp处理表单数据
重新修改 helloworld/helloworld.py :
import cgi import wsgiref.handlers from google.appengine.api import users from google.appengine.ext import webapp class MainPage(webapp.RequestHandler): def get(self): self.response.out.write(""" <html> <body> <form action="/sign" method="post"> <div><textarea name="content" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Sign Guestbook"></div> </form> </body> </html>""") class Guestbook(webapp.RequestHandler): def post(self): self.response.out.write(‘<html><body>You wrote:<pre>‘) self.response.out.write(cgi.escape(self.request.get(‘content‘))) self.response.out.write(‘</pre></body></html>‘) def main(): application = webapp.WSGIApplication( [(‘/‘, MainPage), (‘/sign‘, Guestbook)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
这个页面显示一个输入框,并试图提交一些信息。
这个版本有两个处理过程: MainPage, 对应 URL /, 显示 web 表单. Guestbook, 对应 URL /sign, 显示刚刚提交的信息 .
Guestbook handler 实现了一个post()方法. 如果你需要同时支持 GET 和 POST 方法,你可以同时定义这两个方法 。
代码中的post() 方法通过self.request获取用户提交的数据,并在返回显示结果之前,用cgi.escape()函数对一些HTML中的特殊字符(如<>)进行了处理。 cgi是一个Python标准模块,查看 the documentation for cgi 了解更多相关信息。
Note: App Engine 环境包含了Python2.5中的所有标准库。但是,不是所有方法都是允许的。为了安全性,GAE程序运载在一个受限制的运行环境之中。例如 ,涉及操作系统底层的函数,网络操作,一部门文件操作是不被允许的。如果,你试图调用的话,会提示一个错误。想了解更详细的情况,请查看 The Python Runtime Environment.
接下来…
现在,我们已经可以获取用户提交的数据了,接下来,我们还需要一种方式,把这些信息保存起来。
下一章 使用数据存储.

2008-05-07 12:30
[…] « Google App Engine 入门 :处理表单数据 将Google App Engine应用部署到你的Linux主机上 […]