源码解析flask的路由系统

本文解析了Flask框架的路由系统,详细介绍了app.route装饰器的工作原理,包括如何通过add_url_rule方法处理路由,以及如何使用正则表达式进行路由匹配。通过示例展示了多个路由指向同一视图函数的情况,以及如何利用正则表达式实现复杂URL规则,如限制用户名格式,并处理404错误页面。
摘要由CSDN通过智能技术生成

当我们新建一个flask项目时,pycharm通常已经为项目定义了一个基本路由

@app.route('/')
def hello_world():
    return 'Hello World!'

此时在浏览器中输入地址http://127.0.0.1:5000,页面会显示出"Hello World!"的字样

如下图所示

1133627-20180408212127416-1352244834.png

那么此时在flask后台程序中,到底发生了什么事情呢??

在上面的例子中,可以看到对hello_world视图函数被app.route这个有参装假器装饰

来看下app.route这个有参装饰器的内部实现原理

app是Flask主程序的类实例化本项目名得到的一个对象

app = Flask(__name__)

然后调用app对象的route方法来装饰hello_world视图函数

route方法的源码:

def route(self, rule, **options):
    def decorator(f):
        endpoint = options.pop('endpoint', None)
        self.add_url_rule(rule, endpoint, f, **options)
        return f
    return decorator

在用app.route装饰hello_world视图函数的时候,实际上app.route中还可以添加一些参数。

比如指定请求的方法的变量:methods=["GET","POST"]以及指定视图函数的endpoint,相当于Django中视图函数的别名等

在这里,rule参数相当于hello_world视图函数中的"/"路径,options参数中包含methods和endpoint等

在route装饰器里,返回decorator闭包函数。

在decorator闭包函数中,先从options中获取endpoint的值,endpoint的值默认为None

然后调用self.add_url_rule内部方法处理传递的参数rule,endpoint,f等,在这里self指的是app这个对象

查看app对象中的add_url_rule方法:

    @setupmethod
    def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
    
        if endpoint is None:
            endpoint = _endpoint_from_view_func(view_func)
        options['endpoint'] = endpoint
        methods = options.pop('methods', None)
    
        # if the methods are not given and the view_func object knows its
        # methods we can use that instead.  If neither exists, we go with
        # a tuple of only `
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值