又是Python。呵呵。誰叫人家帥呢
Quixote的部署
在Quixote官方白皮書中已經詳細描述了Quixote的工作模式。Quixote可以使用Python自代的http_server(主要用于開發調試)和與Apache(或lighttpd)配合使用。
Quixote與Apache配合使用方式如下:
- 使用CGI,文檔中稱為egular CGI。被認為效率最低的一種方式,因為每一個請求都會創建一個新的進程。
- 使用fastCGI,CGI可以運行fastCGI一定是可以應用的。這也是豆瓣采用的方式。在Quixote作者的一個PPT中,他認為fastCGI是buggy的。哦:(也不至于啊。我們正在尋找使用fastCGI的部署經驗。
- 使用mod_python,將python代碼嵌入到Apache中。
- 使用SCGI,這是作者推薦的。使用Apache SCGI module scgi_mod將遵循SCGI協議Apache將請求發送到相應的Socket如localhost:3001。而這個Socket由本地運行的一個 Python程序打開。這個Python程序將處理請求,并返回結果。
SCGI的配置
Quixote的網站上對SCGI的描述:SCGI協議是CGI協議的替代。它是一種應用程序與HTTP服務接口標準。它有些像FastCGI但他的設計更容易實現。
配置SCGI過程如下:
- 安裝各個模塊不在話下,debian讓程序員有了懶惰的美德:
#aptitude install libapache2-mod-scgi python-scgi python-quixote
- Apache的配置,添加配置到apache.conf。(有些教程中加入了SetHandler scgi-handler ,但這個加上就很本不會和3000通信。可能是版本的問題。最好不用。)
<Location "/qx">
SCGIServer localost:3000
SCGIHandler On
</Location>
配置完成。SCGI的好處在于,修改了Python程序,不用重啟Apache,只要重啟SCGI就可以了。
第一個Quixote程序
一切就緒,我們來一次Quixote的完整之旅。
- scgi程序要求有一個服務打開3000端口。啟動scgi的程序如下:
1
2 #!/usr/bin/python
3 # -*- coding: utf-8 -*-
4
5 from scgi.quixote_handler import QuixoteHandler, main
6 from quixote import enable_ptl
7 from quixote.publish import Publisher
8 enable_ptl() #啟動PTL
9
10 def create_publisher():
11 from ourroot import RootDirectory
12 return Publisher(RootDirectory(), display_exceptions='plain')
13
14 if __name__ == '__main__':
15 from quixote.server import scgi_server
16 scgi_server.run(create_publisher, port=3000, script_name="/qx")
17
- 程序結構是比較簡單的,使用的是scgi_server的run方法。要注意的是run方法中的script_name和前面apache 的配置Location是一樣的。程序的關鍵是導入了ourroot這樣一個ptl 。下面是我們的第一個ptl程序。
1
2 # -*- coding: utf-8 -*-
3 """這個是我們第一個例子的根目錄
4 """
5 from quixote.directory import Directory
6
7 class RootDirectory(Directory):
8 _q_exports = [""]
9 def _q_index [html] (self):
10 print "debug message from the index page"
11 """
12 <html>
13 <head>
14 <meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
15 <title>第一個例子</title>
16 </head>
17 <body>
18 <h1>第一個例子有中文!</h1>
19 </body>
20 </html>
21 """
22
- 現在在瀏覽器中輸入http://localhost/qx就可以看到結果了。
- 除了運行上面的python腳本,也可以采用這樣的方式運行scgi:
python /var/lib/python-support/python2.5/quixote/server/scgi_server.py \
--factory=FirstApp.create_publisher \
--script-name=/qx --port=3000
Quixote 中文化的要點
Quixote的中文設置好像很麻煩。其實隨著python、Quixote版本的推進,現在這個問題已經很簡單了。字符集使用的是utf-8。使用gb2312可能也是可以的。
- 所有源代碼使用utf-8在程序的開始加上# -*- coding: utf-8 -*-
- ptl的html模板加上content="text/html charset=UTF-8"
- 關鍵:在quixote的安裝路徑下有__init__.py,將其中的DEFAULT_CHARSET = 'iso-8859-1'改成 'utf-8'
- 也可以不修改__init__.py,使用Publisher的時候把Publisher擴展一下:
1 class UTF8Publisher(Publisher):
2 quixote.DEFAULT_CHARSET = "utf-8"