flask裝飾器route實現路由功能理解


  • 利用裝飾器的方式實現了路由函數,這是一個十分簡單清晰的結構,而這個功能的實現,有着很大的學習意義
  • @appweb.route('index',methods=['GET','POST'] def static1(): return render_template('index.html')

    看代碼可以知道,通過appweb.route裝飾了static1()函數,使其成為了路由函數

  • 解析route裝飾器源代碼
  • def route(self,rule,**options): def decorator(f): endpoint = options.pop('endpoints',None) self.add_url_rule(rule,endpoint,f,**options) return f return decorator

    Flask實例的主要路由功能就是這個route函數,而route函數源代碼可以看出,是一個3層嵌套的裝飾器(route函數內部還有個裝飾器)

  • 三層嵌套裝飾器的語法糖規則
  • @appweb.route('index',methods=['GET','POST']) def static1(): return render_template('index.html') #等於
    static1 = appweb.route('index',methods=['GET','POST'])(static1)

     

  • 總結

    上面的route函數,實際上是返回一個decorator,這個decorator函數裝飾static1函數成為路由函數

    route函數的功能是提供rule參數和其他的字典鍵對值參數(**options)

    self.add_url_rule是關鍵的函數,它將f參數(即static1())裝飾成路由函數,最后return f

    關於add_url_rule函數,從更深的源碼可知,默認方法為GET,將rule(即'/index')作為網址注冊進了路由,大部分的參數都在options字典中,目前我已知的參數有methods=,endpoints=,view_func=等

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM