浅析Python的web.py框架中url的设定方法
网页中的数据在传递的时候有GET和POST两种方式,GET是以网址的形式传参数,在web.py中有着很好的匹配,如果我们配置以下的urls urls =( '/','index','/weixin/(.*?)','WeixinInterface' ) 先不考虑/weixin/后面的东西,现在我们来写index的类 class index: def GET(self): i = web.input(name = 'kevinkelin',age = 100) return render.index(i.name,i.age) 随便写一个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! 当访问http://127.0.0.1:8080/ 此时没有传递name与age的值,由于我的GET函数里定义了默认的name与age的值,所以程序会将kevinkelin与26传递到模板中去得到以下的输出 I just want to say hello to kevinkelin,he is 100 years old 当访问http://127.0.0.1:8080/?name=yyx&age=26 即向GET函数中传递name = yyx and age = 26的时候得到以下的输出 I just want to say hello to yyx,he is 26 years old 我们也可以不定义默认的的参数,即定义为空 i = web.input(name = None,age = None) 当访问http://127.0.0.1:8080/ 的时候将会得到 hello,world!的输出即模板中的else i = web.input() 这是因为后面你将i.name与i.age分配到模板当中去,但是全局变量里又没有这两个变量,所以会报错 urls =( '/name=(.*)&age=(.*)','WeixinInterface' ) 重新写class index class index: def GET(self,name,age): return render.index(name,age) 这里是将url的参数通过正则匹配然后传递到index类中的GET的参数中 I just want to say hello to yyx,he is 26 years old 第二种方法看似简单,但其实不好控制,要求写的正则工作量加大了 def POST(self): data = web.data() return data 我想看一下得到的数据类型 return type(data) 得到的是<type 'str'>,也就是说web.py已经将post的数据转换成了str类型 <xml> <ToUserName>yanxingyang</ToUserName> <FromUserName>study_python</FromUserName> <CreateTime>123456</CreateTime> <MsgType>text</MsgType> <Content>Just a test</Content> </xml> 其实这个微信的XML格式做了一些更改,我来试着使用lxml对它进行解析 from lxml import etree data = web.data() xml = etree.fromstring(data) content = xml.find(‘Content').text return content 得到的结果很好 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |