仅供学习,转载请注明出处

前情回顾
前面开发web框架只写到Python web框架开发 - 实现动态页面返回。

思考:这里就存在一个缺陷,虽然页面的确能够返回正确的html页面,但是后续如果不同的页面需要做不同的数据逻辑返回处理,该怎么区分出来呢?
路由功能

根据不同的请求,需要分发路由指向不同的处理逻辑功能。
开发思路
- 根据路径进行匹配,然后指向不同的处理函数
那么如何匹配找出请求过来的路径呢?例如请求过来的路径是./html/index.html
。
此情此景,可以使用正则匹配的方法。
测试如下:
In [1]: import re
In [7]: file_path = "./html/index.py"
In [22]: re.match(r"\./html",file_path).group()
Out[22]: './html'
In [23]: re.match(r"\./html/",file_path).group()
Out[23]: './html/'
In [24]: re.match(r"\./html/[^.]+",file_path).group()
Out[24]: './html/index'
In [25]: re.match(r"\./html/([^.]+)",file_path).group()
Out[25]: './html/index'
In [26]: re.match(r"\./html/([^ ]+)",file_path).group()
Out[26]: './html/index.py'
In [27]: re.match(r"\./html/([^ ]+)",file_path).group(1)
Out[27]: 'index.py'
# 好了,最后根据正则,就可以对应匹配出所需要的函数方法
In [28]: re.match(r"\./html/([^.]+)",file_path).group(1)
Out[28]: 'index'
In [29]:
根据已知的路径,如果找到有结果,那么就可以用返回的结果来进行判断调用哪个服务了。
使用正则匹配,调用不同的函数方法来执行返回数据

测试运行如下:

此时再请求另一个页面:http://127.0.0.1:7788/page_about.py

因为还没有写page_about
的方法,所以没有正常返回页面。
下面再补充一下方法:

再测试一下看看:

好了,能够正常访问了。
通过定义一个路由字典映射不同函数的方法,能够正常根据匹配的函数名,调用不同的方法处理不同页面的逻辑了。
思考:如果这样的方法非常多,那么就要不断得补充这个字典映射表:
# 设置路由对应的字典
route_dict = {
"index" : index,
"page_about" : page_about,
..... 无限添加方法
}
这就比较费劲了。
还有可能会有人疑问,为什么要字典呢?直接使用匹配出来的函数名执行不就好了?因为正则匹配出来的是字符串,无法执行函数的。

优化的方法,写一个修饰器,在调用函数方法的时候,将对应的函数自动写入字典之中,这样就不用自己手动去写了。
编写修饰器,自动将函数写入字典

运行测试一下:

好了,这样就能够正常访问了。不过这种写法需要比较清楚修饰器的使用,如果不清楚的,可以看看我上一篇介绍的文章,点击这里进行访问。

关注微信公众号,回复【资料】、Python、PHP、JAVA、web,则可获得Python、PHP、JAVA、前端等视频资料。
网友评论