如果你希望用户自己可以留言,那么你需要一种处理用户输入信息的办法。而webapp 让数据处理变得很简单。
用webapp处理Web表单的数据
用下面的代码替换helloworld/helloworld.py:
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
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>')
application = webapp.WSGIApplication(
[('/', MainPage),
('/sign', Guestbook)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
重新加载你的程序页面,你将会看到表单,试着写点东西提交吧。
这个版本的程序有两个handler:MainPage, 映射到 URL /, 用来展示表单. Guestbook, 映射到 URL /sign, 用来展示用户提交表单的内容。
Guestbook handler 有一个 post() 方法(而不是get() 方法)。 这是因为用 MainPage 所展示的页面里用了HTTP POST方法 (method="post")来提交表单里的数据。如果你需要在一个类中同时使用这两个方法(post() get()),只需要各自分别定义在一个类下面就可以了。
post() 方法里的代码可以从self.request中获取表单数据,在将这些数据返回并展示给用户之前,它调用了cgi.escape()方法来去掉用户输入中的一些HTML代码标识符。 cgi是标准Python类库中的一个模块,详见the documentation for cgi。
注意:App Engine编程环境包含了所有Python 2.5的标准类库。但是,不是所有的方法都被允许的。App Engine程序与性在一个受限制的环境中,这样App Engine可以安全地将这些程序规模化。比如,底层的一些对于操作系统,网络操作,以及一些文件系统的操作都是不允许的,如果试图调用这些函数,将引发错误。更多信息,请访问The Python Runtime Environment。