• flask-路由系统


    添加路由关系的本质

    • 将url和视图封装成一个Rule对象,添加到Flask的url_map中

    两种添加路由的方式

    # 方式一(FBV)
    
    @app.route('/index', endpoint='index_html')   # endpoint指定的是别名
    def index():
        return render_template('login.html')
    
    # 方式二(CBV)
    
    def index():
        return render_template('login.html')
    
    app.add_url_rule('/index', 'index_html', index)  # index_html是别名
    

    FBV剖析

    FBV是通过装饰器来完成的

    @app.route('/index')
    def index():
        return "Hello"
    
    # app.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('/index')的时候,因为遇到了括号,所以先执行route()函数
    目的是先把()里面的参数保存起来,给内层函数调用(闭包)
    然后就是装饰器的工作流程    
    该装饰器的目的 就是执行了 self.add_url_rule(),把url和被装饰的视图函数绑定起来。
    """
    

    经过FBV剖析之后,得知FBV的装饰器实质上 只是执行了add_url_rule函数,把url和相应的视图函数绑定起来,所以要实现CBV很简单了,直接显式调用add_url_rule即可。

    def index():
        return render_template('login.html')
    
    app.add_url_rule('/index', 'index_html', index)  # index_html是别名
  • 相关阅读:
    行为科学统计第一章知识点总结
    JVM垃圾回收参数说明整理
    RestTemplate
    SparkContext源码阅读
    Spark RDD类源码阅读
    Scala学习笔记
    JAVA虚拟机类型转换学习
    工程开发实用类与方法总结(未完)
    JAVA 几种引用类型学习
    JAVA虚拟机垃圾回收算法原理
  • 原文地址:https://www.cnblogs.com/Xuuuuuu/p/14288894.html
Copyright © 2020-2023  润新知