更新时间:2017-08-09 23:33:26浏览次数:1+次
web.py是python六大web框架之一,尽管创始人以逝世,但是这个框架还是在继续下去,不过不支持python 3。web.py的web请求处理有点restful api的味道,而且其处理请求核心还是在Url映射,我们就是通过url映射匹配来处理业务逻辑的。
web.py有三种url映射匹配:
URL完全匹配(具体的url)
/index
URL模糊匹配(你根本就不知道index后面是什么,它根本不会返回参数)
/index/\d
URL带组匹配(主要有个’()’,它的作用主要是返回参数,你处理的类中一定要有一个参数接受)
/baidu/(.*)
稍后我会给出代码方便理解。
webpy中通过web.input()来保存用户的输入,用户的输入有几种,一种是普通的单个值得输入,另外一种是类似checkbox/list的多个值,还有一种就是上传的文件。对此,请看http://blog.163.com/yang_jianli/blog/static/161990006201510924013595/
最后结合程序来看看url匹配:
#!/usr/bin/env python
# coding: utf-8
import web
urls = (
'/', 'Complete_match',
'/name=(.*)&age=(.*)', 'index',
'/baidu/(.*)', 'hello',
'/news/getnewslist', 'new',
'/(.*)', 'Goup_match',
)
app = web.application(urls, globals())
class Complete_match:
def GET(self):
web.header('Content-type', 'text/html;charset=utf-8') # 防止浏览器编码出错...
param = web.input()
if len(param) != 0:
for p in param:
return param[p]
else:
return "无参数"
class Goup_match:
def GET(self, param):
return param
class index:
def GET(self, name, age):
web.header('Content-type', 'text/html;charset=utf-8') # 防止浏览器编码出错...
return 'name is ' + name + '\r\n' + 'age is ' + age
class hello:
def GET(self, name):
web.header('Content-type', 'text/html;charset=utf-8') # 防止浏览器编码出错...
return 'name is ' + name
class new:
def GET(self):
web.header('Content-type', 'text/html;charset=utf-8') # 防止浏览器编码出错...
# 开始数据库交互
param = web.input()
if len(param) != 0:
for p in param:
return param[p]
else:
return "无参数"
if __name__ == "__main__":
app.run()
代码亲测无错,在这里需要注意下,url的'/'匹配我们应该放在最前面,要不然会出错(反正我已开始没有放在最前面就出错了,调整了下位置就好啦)。看看测试结果:
哈哈哈,你能找到对应url的图嘛?看上面的解释你就能理解了