@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
新聞熱點
疑難解答