這是官方的 Hello world
helloworld.py
import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, webapp2 World!') app = webapp2.WSGIApplication([ ('/', MainPage) ], debug=True)
app.yaml
application: helloworld version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: helloworld.py
若使用 WSGI 來啓動 server,預設的 configuration file 就是 app.yaml,裡面會指明要執行哪個 python code,像上面就是 helloworld.py 這個檔案。執行後會去尋找"app"這個 object,所以物件的命名不能有錯,不然就會出現錯誤:
ERROR 2012-06-20 07:37:47,561 wsgi.py:189] Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 187, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 239, in _LoadHandler raise ImportError('%s has no attribute %s' % (handler, name)) ImportError:has no attribute app
如果不想透過 google app launcher 來啓動 project,請參考這一篇 Quick start (to use webapp2 outside of App Engine),需要額外安裝三個 package。
程式碼如下,要自己另外帶起 http server:
import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, webapp2 World!') app = webapp2.WSGIApplication([ ('/', MainPage) ], debug=True) def main(): from paste import httpserver httpserver.serve(app, host='127.0.0.1', port='8080') if __name__ == '__main__': main()
再從 command line 下達指令就可以了
$ python main.py serving on http://127.0.0.1:8080
沒有留言:
張貼留言