背景:
Python 提供了五花八門的web框架,有功能強大的Django,也有特別方便小巧的Bottle, Karrigell, wxpython,
最近在看《可愛的python》這本書,對於有編程基礎的人,這本書入門python非常好,裏面介紹了Karrigell
這個web框架,它是一個支持python開發web程序的框架,簡單來說,就是可以解釋python腳本的web服務器。
當然,語法不是單純的python腳本,而是python腳本與HTML的結合體。這樣如果按照了Karrigell就可以去打
開一個python腳本寫的界面。
Karrigell的web服務器的功能
1. 提供了4種不同的方法支持python開發web界面(html裏嵌入python,python裏嵌入html等,語法不一樣)
2. 提供多種web服務,支持session管理
3. 自身做爲web服務器解釋頁面,完成請求
4. 可以和其他web服務器(eg:Apache)結合工作,你選擇了Karrigell,仍可使用之前一直在用的web服務器
5. 提供了一個小型的數據庫來和python頁面交互, 當然也支持其他數據庫(eg:Mysql)
下面我們來看一下Karrigell如果操作,以下的步驟都是基於最新的版本,Karrigell-3.1.1。
一、Karrigell 的安裝和運行
1.到SourceForge或者官網下載最新的Karrigell: http://sourceforge.net/projects/karrigell/
2. 如果在linux下面,是Karrigell-3.1.1_core.tar.gz, 使用tar -xvf Karrigell-3.1.1_core.tar.gz 解壓,然後
進入Karrigell-3.1.1_core(可以重命名爲簡單的名字Karrigell),執行python Karrigell.py即可運行.
如果在windows下面,安裝後,直接在Karrigell-3.1.1_core下面雙擊Karrigell.exe文件即可
運行成功的話,窗口會顯示(如下),然後,你就可以運行python網頁了!
Karrigell 3.1.1 running on port 80 (ipv4)
Press Ctrl+C to stop
二、 Karrigell的端口配置和使用
1. 在Karrigell目錄下,有server_config.py(關於服務器的配置信息), 可以看到服務器默認端口是port = 80。
爲了防止和其他web服務衝突,我們一般爲Karrigell要更改服務器端口,我們就把 server_config.py裏面的
port = 8081(可以任意)。這樣再重新運行python Karrigell.py 就出現:
Karrigell 3.1.1 running on port 8081 (ipv4)
Press Ctrl+C to stop
2. Karrigell web服務的主目錄:Karrigell/www (默認)
在瀏覽器上輸入http://localhost:8081,就可以打開Karrigell的主界面,這個界面就是目錄裏面index.py的內容
我們可以試着編寫了一個最簡單的python腳本hello.py (內容是:print "hello world"), 然後在瀏覽器輸入http://localhost:8081/hello.py或者http://localhost:8081/hello
頁面上就顯示了 hello world
三、python腳本和html的結合
我們先看一個《可愛的python》上面列舉的一個小例子hh.py:
def _htmhead(title):
htm = <span style="color:#ff0000;"><strong>"""</strong></span><html> <HEAD>
<meta http-equi v="Content-Type" content = "text/html;charset=utf-8"/>
<title>%s</title></HEAD>
<body><strong><span style="color:#ff0000;">"""</span></strong>%title
return htm
htmfoot= <span style="color:#3366ff;">"""
</span><h5>design by:<a href="abc">Zoom.Quiet</a>
powered by: <a href=<a>http://</a>python.com>Python</a> +
<a href=<a target=_blank href="http://karrigell.com">http://karrigell.com</a>>KARRIGELL2.3.5</a>
</h5>
</body></html><span style="color:#3366ff;">"""</span>
#if __name__=='__main__':
print _htmhead("PyCDC WEB")
print htmfoot
在瀏覽器裏面輸入http://localhost:8081/hh.py之後,頁面顯示:
design by:Zoom.Quiet powered by:Python + KARRIGELL2.3.5
可以看到python和html結合的方法之一是:就是把html頁面的內容用print輸出
1. html中的內容可以使用python中的變量或者函數參數來傳遞值
2. python腳本中的變量可以用html語句形成的字符串表示
3. 然後python腳本中的print將字符串內容打印出來,顯示到頁面上
看個小例子,再感受一下:
<pre class="python" name="code">print "<center>"
print "<a href=http://Sourseforge/project/karrigel>"
print "here is the Karrigell download.</a>"
print "<B>"
print "you can try by yourself."
print "</B>"
print "</center>"
對於web開發的具體過程,我會在後續總結出來,這裏列出參考文章:
http://www.devshed.com/c/a/Python/Karrigell-for-Python/
http://bbs.blueidea.com/thread-2802613-1-1.html (中文翻譯版)
http://blog.csdn.net/xbl1986/article/details/6242634 (Karrigell目錄介紹)