前置作業:
使用 Webapp2 除了 GAE SDK 與之前範例程式碼外,我們還需要下載一個 webapp2.py 的檔案,並將它放置於專案資料夾內。取得檔案指令如下:
wget https://webapp-improved.googlecode.com/hg/webapp2.py建立 Hello World 專案:
依照之前的教學文章為基礎,我們專案資料夾內現在應該有三個檔案,分別是:app.yaml、helloworld.py、webapp2.py。但之前的範例並不是使用 Webapp2,因此我們需要修改 app.yaml 與 helloworld.py 的內容。
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!')
application = webapp2.WSGIApplication([
    ('/', MainPage)
], debug=True)
application: helloworld
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
  script: helloworld.application
至此我們的第一個 Webapp2 專案 Helloworld 所需的檔案都已經完成。以我自己配置為例,專案結構參考如下:
├── google_appengine
│   ├── api_server.py
│   ├── appcfg.py
│   ├── backends_conversion.py
│   ├── BUGS
│   ├── bulkload_client.py
│   ├── bulkloader.py
│   ├── demos
│   ├── dev_appserver.py
│   ├── ...
└── helloworld
    ├── app.yaml
    ├── helloworld.py
    └── webapp2.py
啟動伺服器與測試專案:
專案建立完成後來啟動 Python Development Server 測試我們的專案,以下面的指令啟動後,連線至 http://localhost:8080/ 則可以看到顯示結果。指令參考如下:
# 主要指令,根據你的路徑修改
~/[path]/google_appengine/dev_appserver.py ~/[path]/helloworld/
# 若以我的專案結構為例,指令為:
google_appengine/dev_appserver.py helloworld/
# 加上 host 參數後,可以從其他電腦連至開發伺服器
google_appengine/dev_appserver.py --host 192.168.1.1 helloworld/
Environment :
・ Arch Linux
・ Python 2.7
Reference :
・ Webapp2 official site
・ Python Dev Server information
