轉載請注明:@小五義http://www.cnblogs.com/xiaowuyi
django和webpy都是python的web開發框架。Django的主要目的是簡便、快速的開發數據庫驅動的網站。它強調代碼復用,多個組件可以很方便的以“插件”形式服務於整個框架,Django有許多功能強大的第三方插件,你甚至可以很方便的開發出自己的工具包。這使得Django具有很強的可擴展性。它還強調快速開發和DRY(Do Not Repeat Yourself)原則。webpy小巧,簡單,實用,可以快速的完成簡單的web頁面。這里根據webpy Cookbook簡要的介紹一下webpy框架,更加詳細請見http://webpy.org/cookbook/index.zh-cn。
一、安裝與開發
web.py下載地址:http://webpy.org/static/web.py-0.33.tar.gz。解壓並拷貝web文件夾到你的應用程序目錄下。或者,為了讓所有的應用程序都可以使用,運行:
python setup.py install
注意: 在某些類unix系統上你可能需要切換到root用戶或者運行:
sudo python setup.py install
也可以直接把里面的WEB文件夾放site-packages 。
web.py 內置了web服務器,代碼寫完后,將其保存,例如文件名為mywebpy.py,可以用下面的方法來啟動服務器:
python mywebpy.py
打開你的瀏覽器輸入 http://localhost:8080/ 查看頁面。 若要制定另外的端口,使用 python mywebpy.py 1234。
二、URL 處理
任何網站最重要的部分就是它的URL結構。你的URL並不僅僅只是訪問者所能看到並且能發給朋友的。它還規定了你網站運行的心智模型。在一些類似del.icio.us的流行網站 , URL甚至是UI的一部分。 web.py使這類強大的URL成為可能。
urls = ( '/', 'index' )
第一部分是匹配URL的正則表達式,像/、/help/faq、/item/(\d+)等(\d+將匹配數字)。圓括號表示捕捉對應的數據以便后面使用。第二部分是接受請求的類名稱,像index、view、welcomes.hello (welcomes模塊的hello類),或者get_\1。\1 會被正則表達式捕捉到的內容替換,剩下來捕捉的的內容將被傳遞到你的函數中去。這行表示我們要URL/(首頁)被一個叫index的類處理。現在我們需要創建一個列舉這些url的application。
app = web.application(urls, globals())
這會告訴web.py去創建一個基於我們剛提交的URL列表的application。這個application會在這個文件的全局命名空間中查找對應類。
一般來說,在每個應用的最頂部,你通常會看到整個URL調度模式被定義在元組中:
urls = ( "/tasks/?", "signin", "/tasks/list", "listing", "/tasks/post", "post", "/tasks/chgpass", "chgpass", "/tasks/act", "actions", "/tasks/logout", "logout", "/tasks/signup", "signup" )
這些元組的格式是: URL路徑, 處理類 。
你可以利用強大的正則表達式去設計更靈活的URL路徑。比如 /(test1|test2) 可以捕捉 /test1 或 /test2。要理解這里的關鍵,匹配是依據URL路徑的。比如下面的URL:
http://localhost/myapp/greetings/hello?name=Joe
這個URL的路徑是 /myapp/greetings/hello。web.py會在內部給URL路徑加上和$ ,這樣 /tasks/ 不會匹配 /tasks/addnew。URL匹配依賴於“路徑”,所以不能這樣使用,如: /tasks/delete?name=(.+) ,?之后部分表示是“查詢”,並不會被匹配。閱讀URL組件的更多細節,請訪問web.ctx。
你可以捕捉URL的參數,然后用在處理類中:
/users/list/(.+), "list_users"
在 list/后面的這塊會被捕捉,然后作為參數被用在GET或POST:
class list_users: def GET(self, name): return "Listing info about user: {0}".format(name)
你可以根據需要定義更多參數。同時要注意URL查詢的參數(?后面的內容)也可以用web.input()取得。
三、hello world
現在我們需要來寫index類。雖然大多數人只會看看,並不會注意你的瀏覽器在使用用於與萬維網通信的HTTP語言。具體的細節並不重要,但是要理解web訪問者請求web服務器去根據URL(像/、/foo?f=1)執行一個合適的函數(像GET、POST)的基本思想。GET用於請求網頁文本。當你在瀏覽器輸入harvard.edu,它會直接訪問Harvard的web服務器,去GET /。 POST經常被用在提交form,比如請求買什么東西。每當提交一個去做什么事情(像使用信用卡處理一筆交易)的請求時,你可以使用POST。這是關鍵,因為GET的URL可以被搜索引擎索引,並通過搜索引擎訪問。雖然大部分頁面你希望被索引,但是少數類似訂單處理的頁面你是不希望被索引的。
在我們web.py的代碼中,我們將這兩個方法明確區分:
class index: def GET(self): return "Hello, world!"
當有人用GET請求/時,這個GET函數隨時會被web.py調用。
好了,限制我們只需要最后一句就寫完了。這行會告訴web.py開始提供web頁面:
if __name__ == "__main__": app.run()
這會告訴web.py為我們啟動上面我們寫的應用。
於是將上面的代碼完整列出如下:
import web urls = ( '/', 'index' ) class index: def GET(self): return "Hello, world!" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
保存為hello.py,運行后顯示:
http://0.0.0.0:8080/
在瀏覽器中輸入http://127.0.0.1:8080,就會出現hello world!頁面。
四、模板
給模板新建一個目錄(命名為 templates),在該目錄下新建一個以 .html 結尾的文件,這里存為index.html,內容如下:
<em>Hello</em>, world!
你也可以在模板中使用 web.py 模板支持代碼:
$def with (name) $if name: I just wanted to say <em>hello</em> to $name. $else: <em>Hello</em>, world!
如上,該模板看起來就像 python 文件一樣,除了頂部的 def with (表示從模板將從這后面取值)和總是位於代碼段之前的$。當前,template.py 首先請求模板文件的首行 $def 。當然,你要注意 web.py 將會轉義任何用到的變量,所以當你將name的值設為是一段HTML時,它會被轉義顯示成純文本。如果要關閉該選項,可以寫成 $:name 來代替 $name。
在code.py第一行之下添加:
render = web.template.render('templates/')
這會告訴web.py到你的模板目錄中去查找模板。然后把 index.GET改成: 告訴 web.py 在你的模板目錄下查找模板文件。修改 index.GET :
name = 'Bob' return render.index(name)
完整代碼為:
##@小五義http://www.cnblogs.com/xiaowuyi import web render = web.template.render('templates/') urls = ( '/', 'index' ) class index: def GET(self): name='Bob' return render.index(name) #return "Hello, world!" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
訪問站點它將顯示 I just wanted to say hello to Bob。
但是如果我們想讓用戶自行輸入他的名字,如下:
i = web.input(name=None) return render.index(i.name)
訪問 / 將顯示 hello world,訪問 /?name=Joe 將顯示 I just wanted to say hello to Joe。
URL 的后面的 ? 看起來不好看,修改下 URL 配置:
'/(.*)', 'index'
然后修改下 GET:
def GET(self, name): return render.index(name)
完整代碼為:
##@小五義http://www.cnblogs.com/xiaowuyi import web render = web.template.render('templates/') urls = ( '/(.*)', 'index' ) class index: def GET(self,name): i=web.input(name=None) return render.index(name) #return "Hello, world!" if __name__ == "__main__": app = web.application(urls, globals()) app.run()
現在訪問http://127.0.0.1:8080/TOM ,它會顯示I just wanted to say hello to TOM. 如果訪問http://127.0.0.1:8080/,它會顯示Hello, world!
五、表單
1、簡介
表單包括Textbox、Password 、Textarea 、Dropdown、Radio、Checkbox、Button具體使用及樣式如下:
login = form.Form( form.Textbox('username'), form.Password('password'), form.Password('password_again'), form.Button('Login'), form.Checkbox('YES'), form.Checkbox('NO'), form.Textarea('moe'), form.Dropdown('SEX', ['man', 'woman']), form.Radio('time',['2012-01-01','20120101']), validators = [form.Validator("Passwords didn't match.", lambda i: i.password == i.password_again)] )
顯現在頁面中:
2、輸入屬性
如:
form.textbox("firstname", form.notnull, #put validators first followed by optional attributes class_="textEntry", #gives a class name to the text box -- note the underscore pre="pre", #directly before the text box post="post", #directly after the text box description="please enter your name", #describes field, defaults to form name ("firstname") value="bob", #default value id="nameid", #specify the id )
3、例子:
##code.py ##@小五義http://www.cnblogs.com/xiaowuyi import web,os from web import form render = web.template.render("d:/webpy/templates")##這里仿照http://webpy.org/form#example最初使用了相對路徑templates/,但總是發生找不到formtest的錯誤,於是搜索后,發現換成絕對路徑可以解決這一問題。 urls = ( '/', 'index', ) app = web.application(urls, globals()) login = form.Form( form.Textbox('username'), form.Password('password'), form.Password('password_again'), form.Button('Login'), form.Checkbox('YES'), form.Checkbox('NO'), form.Textarea('moe'), form.Dropdown('SEX', ['man', 'woman']), form.Radio('time',['2012-01-01','20120101']), validators = [form.Validator("Passwords didn't match.", lambda i: i.password == i.password_again)] ) class index: def GET(self): f=login() return render.formtest(f) def POST(self): f=login() if not f.validates(): return render.formtest(f) else: return "HAHA!" if __name__ == "__main__": web.internalerror = web.debugerror app.run()
d:/webpy/templates文件夾下存放formtest.html文件,文件代碼如下:
$def with (form) <form name="main" method="post"> $if not form.valid: <p class="error">Try again,Passwords didn't match:</p> $:form.render() <input type="submit" /> </form>
運行code.py,然后在瀏覽器中瀏覽頁面如下:
填寫表格后,如果兩次password相同,那么會顯示HAHA!,否則顯示Try again, Passwords didn't match:。
六、數據庫
1、數據庫的連接
在開始使用數據庫之前,確保已經安裝了合適的數據庫訪問庫。比如對於MySQL數據庫,使用 MySQLdb ,對於Postgres數據庫使用psycopg2。
創建一個數據庫對象:db = web.database(dbn='postgres', user='username', pw='password', db='dbname')
2、數據庫讀取
例,在數據庫test中有一個表testtable,字段是name,在上面code.py中進行修改,如果login成功,那么列出test表中的內容。
#code.py
##@小五義http://www.cnblogs.com/xiaowuyi import web,os from web import form db = web.database(dbn='postgres', user='postgres', pw='password', db='test') render = web.template.render("d:/webpy/templates") urls = ( '/', 'index', ) app = web.application(urls, globals()) login = form.Form( form.Textbox('username'), form.Password('password'), form.Password('password_again'), form.Button('Login'), form.Checkbox('YES'), form.Checkbox('NO'), form.Textarea('moe'), form.Dropdown('SEX', ['man', 'woman']), form.Radio('time',['2012-01-01','20120101']), validators = [form.Validator("Passwords didn't match.", lambda i: i.password == i.password_again)] ) class index: def GET(self): f=login() return render.formtest(f) def POST(self): f=login() if not f.validates(): return render.formtest(f) else: testtables = db.select('testtable') return render.index(testtables) if __name__ == "__main__": web.internalerror = web.debugerror app.run()
##index.html
$def with (testtables) <ul> $for testtable in testtables: <li id="t$testtable.name">$testtable.name</li> </ul>
當login正確后,會列出testtable表中name字段的值。
3、數據庫寫入
如將上面的FORM表中的user加入到testtable表name字段中,很簡單,只需要在上面的代碼中加入一句:n=db.insert('voa',filename=f['username'].value)。
現在,對code.py代碼進行修改后,當表單填寫正確后,會將username加入到testtable表中,完整代碼如下:
##@小五義http://www.cnblogs.com/xiaowuyi import web,os from web import form db = web.database(dbn='postgres', user='postgres', pw='password', db='bbstime') render = web.template.render("d:/webpy/templates") urls = ( '/', 'index', ) app = web.application(urls, globals()) login = form.Form( form.Textbox('username'), form.Password('password'), form.Password('password_again'), form.Button('Login'), form.Checkbox('YES'), form.Checkbox('NO'), form.Textarea('moe'), form.Dropdown('SEX', ['man', 'woman']), form.Radio('time',['2012-01-01','20120101']), validators = [form.Validator("Passwords didn't match.", lambda i: i.password == i.password_again)] ) class index: def GET(self): f=login() return render.formtest(f) def POST(self): f=login() if not f.validates(): return render.formtest(f) else: n=db.insert('voa',filename=f['username'].value) voas = db.select('voa') return render.index(voas) if __name__ == "__main__": web.internalerror = web.debugerror app.run()