Python web 框架簡述

From:https://www.oschina.net/question/5189_4306

Web.py github 地址:https://github.com/webpy/webpy        https://pypi.python.org/pypi/web.py

Web.py Cookbook 簡體中文版:http://webpy.org/cookbook/index.zh-cn

web.py 0.3 新手指南:http://webpy.org/docs/0.3/tutorial.zh-cn

webpy 官網文檔:http://webpy.org/

web.py 十分鐘創建簡易博客:http://blog.csdn.net/freeking101/article/details/53020728

一個簡單的web.py論壇:http://www.cnblogs.com/russellluo/p/3240564.html

 

web.py 是一個Python 的web 框架,它簡單而且功能強大。web.py 是公開的,無論用於什麼用途都是沒有限制的。而且相當的小巧,應當歸屬於輕量級的web 框架。但這並不影響web.py 的強大,而且使用起來很簡單、很直接。在實際應用上,web.py 更多的是學術上的價值,因爲你可以看到更多web 應用的底層,這在當今“抽象得很好”的web 框架上是學不到的 :) 如果想了解更多web.py,可以訪問web.py 的官方文檔。

先感受一下web.py 的簡單而強大:


 
  1. import web

  2.  
  3. urls = (

  4. '/(.*)', 'hello'

  5. )

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

  8.  
  9. class hello:

  10. def GET(self, name):

  11. i = web.input(times=1)

  12. if not name:

  13. name = 'world'

  14. for c in xrange(int(i.times)):

  15. print 'Hello,', name+'!'

  16. return 'Hello, ' + name + '!'

  17.  
  18. if __name__ == "__main__":

  19. app.run()

上面就是一個基於web.py 的完整的Web 應用。將上面的代碼保存爲文件code.py,在命令行下執行python code.py。然後打開你的瀏覽器,打開地址:http://localhost:8080 或者 http://localhost:8080/test 沒有意外的話(當然要先安裝web.py,下面會有介紹),瀏覽器會顯示“Hello, world”或者 “Hello, test”。

Linux 下運行

這是一個最簡單的Hello world Web 應用。是不是很簡單?!下面將較爲詳細地介紹下web.py 。

 

1. 安裝

下載 web.py 的安裝文件,將下載得到的文件 web.py 解壓,進入解壓後的文件夾,在命令行下執行:python setup.py install,在Linux 等系統下,需要root 的權限,可以執行:sudo python setup.py install。

 

2. URL 處理

對於一個站點來說,URL 的組織是最重要的一個部分,因爲這是用戶看得到的部分,而且直接影響到站點是如何工作的,例如:www.baidu.com ,其URLs 甚至是網頁界面的一部分。而web.py 以簡單的方式就能夠構造出一個強大的URLs。

在每個web.py 應用,必須先import web 模塊:

import web

現在,我們須要告訴web.py URL 如何組織,讓我們以一個簡單例子開始:


 
  1. urls = (

  2. '/', 'index' )

在上面的例子中,第一部分是匹配URL的正則表達式,像//help/faq/item/(\d+)等(\d+將匹配數字)。圓括號表示捕捉對應的數據以便後面使用。第二部分是接受請求的類名稱,像indexviewwelcomes.hello(welcomes模塊的hello類),或者get_\1\1 會被正則表達式捕捉到的內容替換,剩下來捕捉的的內容將被傳遞到你的函數中去。(‘index’)是一個類名,匹配的請求將會被髮送過去。這行表示我們要URL/(首頁)被一個叫index的類處理。

現在我們需要創建一個列舉這些 url 的 application。

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

 

GET 和 POST : 區別

現在,我們需要編寫index 類。當大部人瀏覽網頁的時候,他們都沒有注意到,瀏覽器是通過HTTP 跟World Wide Web 通信的。通信的細節不太重要,但要明白一點,用戶是通過URLs(例如 / 或者 /foo?f=1)來請求web 服務器完成一定請求的(例如 GET 或者POST)。

GET 是最普遍的方法,用來請求一個頁面。當我們在瀏覽器裏輸入“harvard.edu” 的時候,實際上它是向Web 服務器請求GET ”/“。另一個常見的方法是POST,常用於提交特定類型的表單,比如請求買什麼東西。每當提交一個去做什麼事情(像使用信用卡處理一筆交易)的請求時,你可以使用POST。這是關鍵,因爲GET的URL可以明文傳輸提交的參數。如果提交的是一些重要的敏感信息,例如用戶名,密碼,則可能被別人抓包獲取到。而 POST 則不會在 URL 上傳輸 提交的信息,POST 是通過表單提交信息。

在我們的web.py 代碼中。我們清晰區分這兩種方法:


 
  1. class index:

  2. def GET(self):

  3. print "Hello, world!"

當接收到一個GET 請求時,上面的GET 方法將會被web.py 調用。好的。現在,我們只需添加最後一行代碼,讓web.py 啓動網頁應用:


 
  1. if __name__ == "__main__":

  2. app.run()

上面告訴web.py 如何配置URLs,以及找尋的類在文件中的全局命名空間。然後爲我們啓動上面的應用。

整個 code.py 文件的內容如下:


 
  1. import web

  2.  
  3. urls = (

  4. '/(.*)', 'hello'

  5. )

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

  8.  
  9. class hello:

  10. def GET(self, name):

  11. i = web.input(times=1)

  12. if not name:

  13. name = 'world'

  14. for c in xrange(int(i.times)):

  15. print 'Hello,', name+'!'

  16. return 'Hello, ' + name + '!'

  17.  
  18. if __name__ == "__main__":

  19. app.run()

實際上web 應用的代碼就只得上面的幾行,而且這是一個完整的web.py 應用。

 

3.啓動服務

在你的命令行下輸入:


 
  1. $ python code.py # 使用默認端口 8080

  2. 或者

  3. $ python code.py 10000 # 改變端口爲 10000

你的web.py 應用已經啓動了服務器。通過瀏覽器訪問:http://localhost:8080/ ,會見到”Hello, world!“。

修改默認端口

在啓動服務器的時候,如果你不想使用默認端口,你可以使用這樣的命令來指定端口號: python code.py 8888。

 

4. 調試

直接添加一行 web.internalerror = web.debugerror 即可。如下

 


 
  1. if __name__=="__main__":

  2. web.internalerror = web.debugerror

  3. app.run()

 

 

5. 模板

更多關於 web.py templates 可以訪問    http://webpy.org/docs/0.3/templetor.zh-cn

在Python 裏面編寫HTML 代碼是相當累贅的,而在HTML 裏嵌入Python 代碼則有趣得多。幸運地,web.py 使這過程變得相當容易。

注意:舊版本的web.py 是用Cheetah templates 模板的,你可以繼續使用,但官方已不再提供支持。

新建一個 code.py 的 python文件。內容如下:

 


 
  1. import web

  2.  
  3.  
  4. urls = (

  5. # '/(.*)', 'hello',

  6. '/hello_1[/]?.*', 'hello_1',

  7. '/hello_2/(.*)', 'hello_2',

  8. )

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

  11. render=web.template.render('templates')

  12.  
  13. class hello_1:

  14.  
  15. def GET(self):

  16. return render.index_1()

  17.  
  18.  
  19. class hello_2:

  20.  
  21. def GET(self, name):

  22. return render.index_2("Lisa")

  23.  
  24. if __name__ == "__main__":

  25. app.run()

 

創建模板

這裏,我們先在項目 code.py 同一級目錄中新建一個目錄(例如 templates )集中存放並用來組織模板文件,便於管理。然後在templates下新建HTML 文件(例如:”index.html“)。這裏新建 兩個 HTML 文件。 index_1.html 和 index_2.html

index_1.html 文件內容如下:

<em>Hello</em>, world!

這是一個最簡單的html頁面代碼。

index_2.html 文件內容如下:


 
  1. $def with (name)

  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  4. <html xmlns="http://www.w3.org/1999/xhtml">

  5. <head>

  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  7. <title>Template</title>

  8. </head>

  9. <body>

  10. Hi, $name

  11. </body>

  12. </html>

注意上面代碼的縮進!

正如你所見的,上面的模板看上去跟這Python 文件很相似,以def with 語句開始,但在關鍵字前需要添加”$“。

注意:在模板內的變量,如果包含有HTML 標記,以$ 方式引用變量的話,HTML 標記只會以純文本的顯示出來。要想HTML 標記產生效果,可以用$: 引用變量。

 

使用模板

現在,回到 code.py 文件,在”import web” 的下一行添加:

render = web.template.render('templates/')

這告訴web.py 在哪裏可以搜索得到模板目錄。提示:可在render 調用裏添加cache = False 使得每次訪問頁面時都重載模板。

然後再修改使用這個模板的類,在這裏  修改 類 hello_1 和 類 hello_2


 
  1. class hello_1:

  2.  
  3. def GET(self):

  4. return render.index_1()

  5.  
  6.  
  7. class hello_2:

  8.  
  9. def GET(self, name):

  10. # name = "Lisa"

  11. return render.index_2("Lisa")

上面的 ”index_1“ 和 “index_2” 是模板的名字,”Lisa“ 是傳遞過去的參數。

同時修改urls爲:


 
  1. urls = (

  2. # '/(.*)', 'hello',

  3. '/hello_1[/]?.*', 'hello_1',

  4. '/hello_2/(.*)', 'hello_2',

  5. )

上面的“/(.*)” 是一個正則表達式。括號裏面是要傳遞的參數。再將GET 方法修改如下:

 


 
  1. def GET(self,name):

  2. print render.index_2(name)

hello_1 頁面調用 hello_1 類,使用 index_1.html 模板。打開 http://localhost:8080/hello_1 ,頁面就會打印出 Hello, world 的字樣。

hello_2/ 頁面調用 hello_2 類,使用 index_2.html 模板,打開 http://localhost:8080/hello_2/,頁面就會打印出 Hello, Lisa 的字樣。

 

除此之外還有兩種使用模板的方法

  1. 使用frender直接指定模板文件。GET函數最後兩行改爲
    
     
    1. render=web.template.frender("templates/index.html")

    2. return render("Lisa")

  2. 直接在代碼裏寫出模板文件。GET最後兩行改爲
    
     
    1. template = "$def with (name)\nHello $name"

    2. render = web.template.Template(template)

    3. return render("Lisa")

 

模板含義

現在解釋一下這個 index.html 模板的含義:


 
  1. $def with (name)

  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  4. <html xmlns="http://www.w3.org/1999/xhtml">

  5. <head>

  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  7. <title>Template</title>

  8. </head>

  9. <body>

  10. Hi, $name

  11. </body>

  12. </html>

在index.html第一行 $def with (name)表示本模板接受一個名爲name的參數,也就是對應index類中return render.index(“Lisa”)中的Lisa。

而render=web.template.render(“templates”)表示創建一個模板對象,模板是存放於templates目錄下,然後就可以用所創建的 render 對象來訪問相應的模板

比如templates目錄下的index.html就是用render.index來表示(實際上是匹配尋找index.*文件,第一個匹配的就認爲是所對應的模板文件),如果templates下還有個a目錄,a目錄下有個pagea.html,那麼訪問這個pagea模板就要用render.a.pagea的形式了。

 

頁面參數

頁面接收的參數可以多於一個,也可以沒有,如果不需要參數,則就不需要$def with (name)這樣的代碼,刪除掉這一句,同時修改模板中對name變量的引用,修改index類最後一句爲return render.index()就可以了。
 

如果有參數,那麼模板的第一行代碼就必須是這個 $def with (…),可以多於一個參數,比如是這樣$def with (gname, fname)。

模板下面的那行字改爲Hi, $gname $fname。

同時Index類GET返回的時候賦予對應兩個參數return render.index(“Lisa”,”Hayes”)。

這樣,頁面最後顯示的是打印出Hi, Lisa Hayes的字樣。

另外,模板接受的這個參數也可以是一個元組,比如像下面這樣:return render.index((“Lisa”,”Hayes”))

在模板中可以如下以元組方式訪問參數數據:Hi, $name[0] $name[1]

 

模板語法

模板語法與python語法基本一致,主要差別可以從上面的代碼中看到,要使用到$符號表明這不是文本而是模板代碼。也就是每當用到程序代碼、對象的時候就必須用$來與html代碼和頁面顯示文本相區別。

 

對象賦值

向對象賦值時需要在$與對象名之間留空格,如爲一個名爲vara的字符串對象賦值apple的代碼爲$ vara = “apple”。
另外,對象賦值語句必須獨佔一行,前面或後面有其他代碼則會程序出錯。

 

對象引用

引用對象的時候直接使用 $+對象名的形式,如$vara。
另外引用對象時還可以用{}或()將對象進行明確的分組,如$(vara)s就會表示apples,如果沒有括號,程序則會把 $varas作爲一個整體,也就變成對varas對象的引用而發生錯誤。另如果像如下定義兩個數字型對象:


 
  1. $varb = 1

  2. $varc = 2

然後希望計算兩個值的和,如果用$varb+$varc的形式,頁面上只會得到1+2而不是3,這時也就需要把兩個對象放在括號裏,如$(varb+varc)的形式才能得到正確答案3。

 

註釋

模板中支持單行註釋,以$#符號開始到行末都是註釋內容。
$#This is comment
註釋前面可以有其他內容,但是不可以有賦值代碼。
如下代碼是正確的:Hi $#This is comment
但下面的則會出錯:$ vara = “apple” $#This is comment

 

打印$符號

由於$符號在模板中有特殊用途,所以在頁面上輸出$時需要進行轉義操作,用連續兩個$表示在頁面上輸出一個$符號。

Can you lend me $50?

 

控制代碼(循環、條件判斷)

模板中支持for、while、if、elif、else,用法與在python一致,只是控制代碼行要以$開始(包括break和continue命令),$開始的代碼行中對象不需要在前面再加$符號,同時要注意縮進規則,如:

for 循環:


 
  1. $def with (toUser,fromUser,createTime,articleCnt,articles)

  2. <xml>

  3. <ToUserName><![CDATA[$toUser]]></ToUserName>

  4. <FromUserName><![CDATA[$fromUser]]></FromUserName>

  5. <CreateTime>$createTime</CreateTime>

  6. <MsgType><![CDATA[news]]></MsgType>

  7. <ArticleCount>$articleCnt</ArticleCount>

  8. <Articles>

  9. $for a in articles:

  10. <item>

  11. <Title><![CDATA[$a['title']]]></Title>

  12. <Description><![CDATA[$a['desc']]]></Description>

  13. <PicUrl><![CDATA[$a['picUrl']]]></PicUrl>

  14. <Url><![CDATA[$a['url']]]></Url>

  15. </item>

  16. </Articles>

  17. </xml>

if else判斷:


 
  1. $if times > max:

  2. Stop! In the name of love.

  3. $else:

  4. Keep on, you can do it.

在for循環中,有一組內置的變量可以使用,非常方便,分別如下所示:

  • loop.index: 循環次數計數 (1-開始)
  • loop.index0: 循環次數計數(0-開始)
  • loop.first: 如果是第一次循環則爲True
  • loop.last: 如果是最後一次循環則爲True
  • loop.odd: 如果是第奇數次循環則爲True
  • loop.even: 如果是第偶數次循環則爲True
  • loop.parity: 如果循環次數爲奇數值爲“odd” ,反之爲 “even”
  • loop.parent: 本循環的外層循環對象

 
  1. $for a in ["a", "b", "c", "d"]:

  2. $loop.index,$loop.index0,$loop.first,$loop.last,$loop.odd,$loop.even,$loop.parity<br/>

將在頁面上打印出:


 
  1. 1,0,True,False,True,False,odd

  2. 2,1,False,False,False,True,even

  3. 3,2,False,False,True,False,odd

  4. 4,3,False,True,False,True,even

 

函數-$def

函數定義也是與在python中類似,用def,只是也要在前面加$,代碼也要注意$的使用和縮進:


 
  1. $def hello(name=""):

  2. Hello $name!

函數調用也是用$加函數名的形式:

$hello("Lisa")

當然,定義函數時也可以與html代碼混編:


 
  1. $def hello(name=""):

  2. <strong/>Hello $name!</strong>

但是調用的時候需要在函數名前用$:前綴,否則html代碼將以plain text形式打印到頁面上。

$:hello("Lisa")

 

 

輸出程序代碼-$code塊

如果想在模板裏輸入寫一段python代碼而又不想被$所煩惱,那麼可以用到$code塊。

頁面上輸出一段代碼而不希望被系統理解爲模板程序代碼,就需要用到$code命令,比如在模板文件中寫入下面一段:


 
  1. $code:

  2. x=10

  3. def print_num(num):

  4. return "num is %d" % num

然後再加上下面代碼:


 
  1. $print_num(x)

  2. <br/>

  3. $x

這裏就用在$code塊中定義的print_num函數以x變量爲參數在頁面上輸出一行:num is 10

然後下一行直接引用x變量,直接在頁面上輸出數字10。

 

$var

$var命令可以在模板中定義變量,在其他地方引用此模板對象的時候可以訪問此定義的變量。
比如我們可以在index.html中添加如下一行:$var vara: this is vara
表示定義了一個名爲vara的變量,變量值是字符串this is vara。
把index的GET函數改爲:


 
  1. def GET(self):

  2. render=web.template.render("templates")

  3. return render.index("Lisa", "Hayes").vara

那麼結果顯示在頁面上的就是this is vara這句話。要注意一點的是,這種變量是字符串,即便如下定義變量:$var vara: 0

Vara也並不是數字0,如果把GET函數最後改成:return render.index(“Lisa”, “Hayes”).vara+1

會導致程序出錯。如果希望得到期望中的結果1,則需要如下形式代碼:return int(render.index(“Lisa”, “Hayes”).vara)+1

 

builtins and globals

在模板中,用戶可以直接使用python的內建函數和變量,寫函數變量包括range, min, max 以及 True 和 False等。 除此之外,如果希望在模板中使用其他的非內建功能,就需要一點特殊操作。要在創建render的時候顯式指定所需要的功能函數。


 
  1. import web

  2. import markdown

  3.  
  4. globals = {'markdown': markdown.markdown}

  5. render =web.template.render('templates', globals=globals)

這樣,在模板中就可以用$markdown來引用markdown.markdown了。同樣,也可以用這種辦法來禁用builtins


 
  1. # disable all builtins

  2. render = web.template.render('templates', builtins={})

 

模板複用

當多個頁面有着相同的結構框架的時候,爲每一個頁面單獨維護一個模板就顯得比較麻煩,web.py提供了一種簡易的解決方法。
這時候就要用到創建render時使用base參數:


 
  1. render=web.template.render("templates",base="layout")

  2. return render.index("Lisa", "Hayes")

這個layout表示要以templates下的layout.html模板爲通用模板框架。因此我們還要在templates目錄下新建一個layout.html文件,寫下如下代碼:


 
  1. $def with (content)

  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  3. <html xmlns="http://www.w3.org/1999/xhtml">

  4. <head>

  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  6. <title>Layout</title>

  7. </head>

  8. <body>

  9. $:content

  10. </body>

  11. </html>

可以看到,這個模板文件必須是有一個參數content。然後修改index.html,只保留如下代碼,其他刪掉:


 
  1. $def with(gname, fname)

  2. Hi, $(gname) $(fname)

運行程序,頁面上打印Hi, Lisa Hayes,查看代碼會發現最終代碼就是index.html和layout.html合併在一起的結果,index.html中的內容被嵌入到layout.html中的$:content處。
在layout.html模板中還可以引用index.html中定義的var變量,這爲程序帶來了更多的靈活性,比如我們希望在不同的頁面在使用同一個layout模板的時候能有不同的title,可以在使用layout的模板中定義如下一個var變量:$var title:This is index.html
然後在layout.html中的title處修改爲:<title>$content.title</title>
這樣,訪問index.html時顯示在瀏覽器上的title就是This is index.html,而不是原來的Layout了。

 

在模板中使用python代碼模塊

在默認狀態下,在模板中是不能直接調用其他python代碼模塊文件中的程序的,必須做一些額外的操作。
首先,我們新建一個模塊,叫module1.py,在裏面寫一個函數:


 
  1. def hello_from_m1(name=""):

  2. return "hello %s, this is module1" % name

在main.py裏導入module1:import module1

並且修改GET函數中創建render的代碼爲:


 
  1. def GET(self):

  2. render=web.template.render("templates",base="layout",globals={"m1":module1})

  3. return render.index("Lisa")

globals參數中傳遞的是一個字典,key以字符串表示模塊在模板中使用時的名稱,value部分就是這個要在模塊中使用的模塊或對象的真實名稱了。
最後在要使用此模塊的模板中就可以用$m1來引用此模塊了。比如在index.html中添加下面一行代碼:$m1.hello_from_m1(gname)
就會調用module1中的hello_from_m1函數,在頁面上打印出:hello Lisa, this is module1

 

在web.py模板中使用jQuery

在jQuery中$也是一個關鍵字,這樣的話如果在模板中使用jQuery就會衝突,這時候只需要用$做一下轉義就可以了,比如:


 
  1. <script type="text/javascript">

  2. $(document).ready(function()

  3. {

  4. alert("It works.");

  5. });

  6. </script>

 

6. 數據庫

 

Web.py 更多關於數據庫的操作:http://webpy.org/cookbook/index.zh-cn

注意:在你開始連接數據庫之前,請先安裝正確的數據庫驅動。比如 MySQLdb、psycopg2。如果需要嘗試連接 池(database pool)功能,還得裝下DBUtils。這幾個模塊都可以通過easy_install 或者 pip 來安裝。

連接數據庫:

 


 
  1. import web

  2. db = web.database(dbn='postgres', db='mydata', user='dbuser', pw='')

操作 數據庫 示例


 
  1. select 查詢

  2. # 查詢表

  3. entries = db.select('mytable')

  4. # where 條件

  5. myvar = dict(name="Bob")

  6. results = db.select('mytable', myvar, where="name = $name")

  7. results = db.select('mytable', where="id>100")

  8. # 查詢具體列

  9. results = db.select('mytable', what="id,name")

  10. # order by

  11. results = db.select('mytable', order="post_date DESC")

  12. # group

  13. results = db.select('mytable', group="color")

  14. # limit

  15. results = db.select('mytable', limit=10)

  16. # offset

  17. results = db.select('mytable', offset=10)

  18.  
  19.  
  20. 更新

  21. db.update('mytable', where="id = 10", value1 = "foo")

  22.  
  23.  
  24. 刪除

  25. db.delete('mytable', where="id=10")

  26.  
  27.  
  28. 複雜查詢

  29. # count

  30. results = db.query("SELECT COUNT(*) AS total_users FROM users")

  31. print results[0].total_users

  32. # join

  33. results = db.query("SELECT * FROM entries JOIN users WHERE entries.author_id = users.id")

  34. # 防止SQL注入可以這麼幹

  35. results = db.query("SELECT * FROM users WHERE id=$id", vars={'id':10})

  36.  
  37.  
  38. 多數據庫操作 (web.py大於0.3)

  39. db1 = web.database(dbn='mysql', db='dbname1', user='foo')

  40. db2 = web.database(dbn='mysql', db='dbname2', user='foo')

  41. print db1.select('foo', where='id=1')

  42. print db2.select('bar', where='id=5')

  43.  
  44.  
  45. 事務

  46. t = db.transaction()

  47. try:

  48. db.insert('person', name='foo')

  49. db.insert('person', name='bar')

  50. except:

  51. t.rollback()

  52. raise

  53. else:

  54. t.commit()

  55.  
  56. # Python 2.5+ 可以用with

  57. from __future__ import with_statement

  58. with db.transaction():

  59. db.insert('person', name='foo')

  60. db.insert('person', name='bar')

現在,在數據庫裏創建一個簡單的表:


 
  1. CREATE TABLE todo (

  2. id serial primary key,

  3. title text,

  4. created timestamp default now(),

  5. done boolean default 'f'

  6. );

  7.  
  8.  
  9. /* 初始化一行 */

  10. INSERT INTO todo (title) VALUES ('Learn web.py');

回到 code.py,修改GET 方法如下:


 
  1. def GET(self):

  2. todos = db.select('todo')

  3. print render.index(todos)

修改urls 變量:


 
  1. urls = (

  2. '/', 'index')

重新編輯index.html 文件如下:


 
  1. $def with (todos)

  2. <ul>

  3. $for todo in todos:

  4. <li id="t$todo.id">$todo.title</li>

  5. </ul>

現在,可以訪問”/“,如果顯示”Learn web.py“,則祝賀你成功了!

現在,再讓我們看看如何向數據庫寫入。在index.html 文件的尾部添加如下內容:


 
  1. <form method="post" action="add">

  2. <p>

  3. <input type="text" name="title" />

  4. <input type="submit" value="Add" />

  5. </p>

  6. </form>

修改code.py 文件的urls 變量如下:


 
  1. urls = (

  2. '/', 'index',

  3. '/add', 'add'

  4. )

在code.py 裏添加一個類:


 
  1. class add:

  2. def POST(self):

  3. i = web.input()

  4. n = db.insert('todo', title=i.title)

  5. web.seeother('/')

web.input 使你能夠方便地訪問用戶通過表單提交上來的變量。db.insert 用於向數據庫的 “todo” 表插入數據,並且返回新插入行的ID。web.seeother 用於重轉向到”/“。

提示:對於數據庫的操作,還有db.transact(), db.commit(), db.rollback(),db.update()。

在web.py 裏,還有web.input,web.query 和其它的函數,返回”Storage objects”,可以像字典型類(dictionaries) 的使用。

 

使用 Web.py 搭建一個測試網站案例

 

Web.py Form庫文檔 和 示例代碼 :http://webpy.org/form

參考 http://blog.csdn.net/freeking101/article/details/76148434  這篇文章改寫成 Web.py 搭建測試網站

 

先看 官網一個使用 Form 表單的示例(code.py):

 


 
  1. import web

  2. from web import form

  3.  
  4. render = web.template.render('templates/')

  5.  
  6. urls = ('/', 'index')

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

  8.  
  9. myform = form.Form(

  10. form.Textbox("boe"),

  11. form.Textbox("bax",

  12. form.notnull,

  13. form.regexp('\d+', 'Must be a digit'),

  14. form.Validator('Must be more than 5', lambda x:int(x)>5)),

  15. form.Textarea('moe'),

  16. form.Checkbox('curly'),

  17. form.Dropdown('french', ['mustard', 'fries', 'wine']))

  18.  
  19. class index:

  20. def GET(self):

  21. form = myform()

  22. # make sure you create a copy of the form by calling it (line above)

  23. # Otherwise changes will appear globally

  24. print(form.render())

  25. return render.formtest(form)

  26.  
  27. def POST(self):

  28. form = myform()

  29. if not form.validates():

  30. print(form.render())

  31. return render.formtest(form)

  32. else:

  33. # form.d.boe and form['boe'].value are equivalent ways of

  34. # extracting the validated arguments from the form.

  35. return "Grrreat success! boe: %s, bax: %s" % (form.d.boe, form['bax'].value)

  36.  
  37. if __name__=="__main__":

  38. web.internalerror = web.debugerror

  39. app.run()

 

formtest.html 代碼如下:

 


 
  1. $def with (form)

  2.  
  3. <div align="center">

  4. <form name="main" method="post">

  5. $if not form.valid: <p class="error">Try again, AmeriCAN:</p>

  6. $:form.render()

  7. <input type="submit" />

  8. </form>

  9. <div>

 

Linux 下運行結果

然後根據上面內容開始改寫 自己的網站

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章