@app.route(), 是調用了flask.app.py文件里面的Flask類的route方法,route方法所做的事情和add_url_rule類似,是用來為一個URL注冊一個視圖函數,但是我們知道route方法是以裝飾器的方式使用的

def route(self, rule, **options): """sage:: @app.route('/') def index(): return 'Hello World' :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator
參數解析
- rule: 一個字符串格式的url規則,如:"/login"
- endpont: 被注冊的url的名字,一般用來反向生成url的時候使用,默認把視圖函數的名字作為endpoint,如:endpoint="login"
- **options: 這個options是跟隨:class:`~werkzeug.routing.Rule` object定義的,后面會分析這個對象中的具體參數,但有一個methods參數默認是只監聽get方法。
函數體解析
# 根據route的裝飾器使用方法,我們可以知道f參數就是視圖函數。 def decorator(f): # 如果options參數中有endpoint則彈出endpoint,並把值賦值給endpoint變量,如果沒有則賦值為None endpoint = options.pop('endpoint', None) # 調用add_url_rule方法,並把rule,endpont,f,**options傳遞進來,並執行這個方法,詳見add_url_rule方法源碼分析 self.add_url_rule(rule, endpoint, f, **options) # 返回了返回f return f