Sep 16, 2009

Google App Engine

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()
1. 要熟悉 webapp.RequestHandler
webapp.RequestHandler.response 响应
webapp.RequestHandler.request 请求的信息

2. 流程说明
参见 url 的解释,'/'路径 使用 MainPage 处理,MainPage 有 get 函数,响应一个 HTML 文件,包含一个表单,表单中指明使用 post 命令,post 到 /sign 路径。
/sign 路径使用 Guestbook 处理,它应该有 post 函数。

开发流程:
1. 本地服务器
C:\Program Files\Google\google_appengine>c:\Python25\python.exe dev_appserver.py
 ./kchsjtu
浏览器 http://localhost:8080 访问

2. 上传程序
先登录google app engine, 创建所需的程序,譬如 kchsjtu
再本地上传
C:\Program Files\Google\google_appengine>c:\Python25\python.exe appcfg.py update
 kchsjtu\

一个最简单的程序

import cgi

import urllib
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="Fetch the URL"></div>
          </form>
        </body>
      </html>""")


class Guestbook(webapp.RequestHandler):
  def post(self):
    url=cgi.escape(self.request.get('content'))
    response = urllib.urlopen(url)
    the_page = response.read()
    self.response.out.write(the_page)


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/sign', Guestbook)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

存在的问题:
  • 现在必须填写 http://
  • 中文不支持

0 comments: