天天看點

web.py輕量級開發架構——python的超輕量級伺服器

web.py輕量級開發架構——python的超輕量級伺服器

運作環境:

作業系統:Ubuntu 12.04 STL 

python版本:2.7.5

1.安裝web.py 

打開終端,執行指令:

sudo easy_install web.py      

2.安裝lpthw.web 

安裝lpthw.web的目的純粹是為了列印log,便于背景檢視, 

依舊在終端中,運作指令:

sudo pip install lpthw.web      

OK,此時開始寫一個簡單的程式試一下: 

執行如下指令:

mkdir karlweb
cd karlweb
mkdir bin gothonweb tests docs templates
touch bin/app.py
touch templates/index.html      

此時,一個web.py的項目建立完畢,接下來開始編輯, 

執行如下代碼:

vi bin/app.py      

然後輸入如下代碼:

import web

urls =('/','Index',#url位址的映射'/book','Book')

app = web.application(urls, globals())

render = web.template.render('templates/')classIndex(object):#此類與‘/’位址映射def GET(self):
		greeting ="Hello World"return render.index(greeting = greeting)classBook(object):#此類與‘/book’位址映射def GET(self):return render.book()if __name__ =="__main__":
	app.run()      

儲存并退出,執行如下指令:

touch templates/index.html
vi templates/index.html      

輸入如下代碼:

$def with(greeting)<html><head><title>Web.py test</title></head><body>

$if greeting:
	I just wanted to say <em style="color: green; font-size: 2em;">$greeting</em>.
$else:<em>Hello</em>, world!</body></html>      

此時,運作如如下代碼:

python bin/app.py      

然後通路localhost:8080/就會出現如下效果: 

I just wanted to say Hello World . 

這時,我們再執行如下指令:

touch templates/book.html
vi templates/book.html      

輸入如下代碼:

<html><head><title>BOOK</title></head><body><center>BOOK</center></body></html>      

然後我們通路localhost:8080/book将會看到浏覽器顯示BOOK。 

從上面的過程可以看出webpy比較不錯的內建了mvc設計模式,實作了多層架構, 

而且webpy非常輕量級,值得程式開發人員學習一下

繼續閱讀