
- TurboGears 教程
- TurboGears - 首頁
- TurboGears - 概述
- TurboGears - 環境
- TurboGears - 第一個程式
- TurboGears - 依賴項
- TurboGears - 服務模板
- TurboGears - HTTP 方法
- Genshi 模板語言
- TurboGears - 包含
- TurboGears - JSON 渲染
- TurboGears - URL 層次結構
- TurboGears - Toscawidgets 表單
- TurboGears - 驗證
- TurboGears - 快閃記憶體訊息
- TurboGears - Cookie 和會話
- TurboGears - 快取
- TurboGears - SQLAlchemy
- TurboGears - 建立模型
- TurboGears - CRUD 操作
- TurboGears - 資料網格
- TurboGears - 分頁
- TurboGears - 管理員訪問
- 授權和認證
- TurboGears - 使用 MongoDB
- TurboGears - 腳手架
- TurboGears - 鉤子
- TurboGears - 編寫擴充套件
- TurboGears - 可插拔應用程式
- TurboGears - RESTful 應用程式
- TurboGears - 部署
- TurboGears 有用資源
- TurboGears - 快速指南
- TurboGears - 有用資源
- TurboGears - 討論
TurboGears - 第一個程式
TurboGears 具有極簡模式,可以快速建立單個檔案應用程式。可以使用最少的依賴項快速構建簡單的示例和服務。
TG 應用程式中的 Application 類繼承自 **TGController** 類。此類中的方法可透過 **tg** 模組中的 **@expose** 裝飾器訪問。在我們的第一個應用程式中,**index()** 方法被對映為應用程式的根。TGController 類也需要從 **tg** 模組匯入。
from tg import expose, TGController class MyController(TGController): @expose() def index(self): return 'Hello World turbogears'
接下來,設定應用程式的配置並宣告應用程式物件。此處的 **AppConfig** 類建構函式採用兩個引數 - 將 minimal 屬性設定為 true 和控制器類。
config = AppConfig(minimal = True, root_controller = RootController()) application = config.make_wsgi_app()
此處的 **make_wsgi_app()** 函式構建應用程式物件。
為了服務此應用程式,我們現在需要啟動 HTTP 伺服器。如前所述,我們將使用 **wsgiref** 包中的 **simple_server** 模組來設定和啟動它。此模組具有 **make_server()** 方法,該方法需要埠號和應用程式物件作為引數。
from wsgiref.simple_server import make_server server = make_server('', 8080, application) server.serve_forever()
這意味著我們的應用程式將在本地主機的 8080 埠上提供服務。
以下是我們的第一個 TurboGears 應用程式的完整程式碼:
app.py
from wsgiref.simple_server import make_server from tg import expose, TGController, AppConfig class MyController(TGController): @expose() def index(self): return 'Hello World TurboGears' config = AppConfig(minimal = True, root_controller = MyController()) application = config.make_wsgi_app() print "Serving on port 8080..." server = make_server('', 8080, application) server.serve_forever()
從 Python shell 執行上述指令碼。
Python app.py
在瀏覽器的位址列中輸入 **https://:8080** 以檢視“Hello World TurboGears”訊息。
TurboGears 的 **tg.devtools** 包含 Gearbox。它是一組命令,可用於管理更復雜的 TG 專案。可以透過以下 Gearbox 命令快速建立全棧專案:
gearbox quickstart HelloWorld
這將建立一個名為 **HelloWorld** 的專案。
廣告