欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺析Python的web.py框架中url的設(shè)定方法

 更新時(shí)間:2016年07月11日 19:50:03   作者:Kevin_Yang  
web.py是Python的一個(gè)輕量級(jí)Web開發(fā)框架,這里我們來淺析Python的web.py框架中url的設(shè)定方法,需要的朋友可以參考下

網(wǎng)頁中的數(shù)據(jù)在傳遞的時(shí)候有GET和POST兩種方式,GET是以網(wǎng)址的形式傳參數(shù),在web.py中有著很好的匹配,如果我們配置以下的urls

 urls =(
  '/','index',
  '/weixin/(.*?)','WeixinInterface'
  
  )

先不考慮/weixin/后面的東西,現(xiàn)在我們來寫index的類

 class index:
  def GET(self):
    i = web.input(name = 'kevinkelin',age = 100)     
    return render.index(i.name,i.age)

隨便寫一個(gè)index.html模板文件

 $def with(name,age)
$if name:
  I just want to say <em>hello</em> to $name, he is $age years old
$else:
  <em>hello</em>,world!

當(dāng)訪問http://127.0.0.1:8080/ 此時(shí)沒有傳遞name與age的值,由于我的GET函數(shù)里定義了默認(rèn)的name與age的值,所以程序會(huì)將kevinkelin與26傳遞到模板中去得到以下的輸出

I just want to say hello to kevinkelin, he is 100 years old

當(dāng)訪問http://127.0.0.1:8080/?name=yyx&age=26 即向GET函數(shù)中傳遞name = yyx and age = 26的時(shí)候得到以下的輸出

I just want to say hello to yyx, he is 26 years old

 我們也可以不定義默認(rèn)的的參數(shù),即定義為空

i = web.input(name = None,age = None)

當(dāng)訪問http://127.0.0.1:8080/ 的時(shí)候?qū)?huì)得到 hello,world!的輸出即模板中的else
但是如果你不定義name和age將會(huì)出錯(cuò)

i = web.input()

這是因?yàn)楹竺婺銓.name與i.age分配到模板當(dāng)中去,但是全局變量里又沒有這兩個(gè)變量,所以會(huì)報(bào)錯(cuò)
但有時(shí)我們想這樣傳遞參數(shù),不想加那個(gè)“?”這時(shí)我們得要更改urls規(guī)則

 urls =(
  '/name=(.*)&age=(.*)','index',
  '/weixin/(.*?)','WeixinInterface'  
  )

重新寫class index

 class index:
  def GET(self,name,age):
    return render.index(name,age)

這里是將url的參數(shù)通過正則匹配然后傳遞到index類中的GET的參數(shù)中
當(dāng)訪問http://127.0.0.1:8080/name=yyx&age=26 時(shí)將得到

I just want to say hello to yyx, he is 26 years old

第二種方法看似簡(jiǎn)單,但其實(shí)不好控制,要求寫的正則工作量加大了
如果我想知道到底有多少參數(shù)通過GET方式傳遞過來,我可以直接return 來看一下到底有哪些傳遞過來了
接下來看一下post來的數(shù)據(jù):
我們可以制作一個(gè)簡(jiǎn)單的表單或者直接使用fiddler來構(gòu)造數(shù)據(jù)進(jìn)行POST傳值 

def POST(self):
    data = web.data()    
    return data

2016711194530065.png (698×539)

我想看一下得到的數(shù)據(jù)類型

return type(data)

得到的是<type 'str'>,也就是說web.py已經(jīng)將post的數(shù)據(jù)轉(zhuǎn)換成了str類型
那么我來試一下傳遞xml

 <xml>
<ToUserName>yanxingyang</ToUserName>
<FromUserName>study_python</FromUserName>
<CreateTime>123456</CreateTime>
<MsgType>text</MsgType>
<Content>Just a test</Content>
</xml>

其實(shí)這個(gè)微信的XML格式做了一些更改,我來試著使用lxml對(duì)它進(jìn)行解析

from lxml import etree
data = web.data()
xml = etree.fromstring(data)
content = xml.find(‘Content').text
return content

得到的結(jié)果很好

2016711194622132.png (244×124)

相關(guān)文章

最新評(píng)論