from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'ok'
if __name__ == '__main__':
app.run()
この単純なコードの入力から、どのようなルートを分析します@app.route('/')
ルートは():インデックスにプラスである()デコレータ
def route(self, rule, **options): # rule:匹配规则,options参数字典
def decorator(f):
endpoint = options.pop("endpoint", None) # 如果option中有endpoint就取出,否则endpoint=None
self.add_url_rule(rule, endpoint, f, **options) # f就是装饰器装饰的视图函数 index
return f
return decorator
情報を取得します。
(1)場合、基準伝送経路指定することができendpoint = '别名'
、逆解析として、エンドポイントエイリアスを取るべきルートは、後で再び説明します。時間はいずれも合格しませんでした。
(2)それが機能するためにビュー経路と所定の対応関係を追加add_url_ruleのマッチング方法の実装であります
add_url_rule():ルートに機能を追加するビューと所定の対応関係に合致
@setupmethod
def add_url_rule(self,rule,endpoint=None,view_func=None,provide_automatic_options=None,**options):
# 其中rule是必须要传入的,endpoint是别名,view_func是函数名
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func) # 如果没有别名就执行该函数,并且将视图函数当做参数传入了,稍后再看
options["endpoint"] = endpoint
methods = options.pop("methods", None) # 如果options中有methods则取出,否则为methods = None
# 如果methods为None的话,默认为view_func中的methods属性值,或者为('GET',)请求
if methods is None:
methods = getattr(view_func, "methods", None) or ("GET",)
# 如果methods是字符串类型,string_types=>(str, unicode),则抛出异常
if isinstance(methods, string_types):
raise TypeError(
"Allowed methods have to be iterables of strings, "
'for example: @app.route(..., methods=["POST"])'
)
# 循环遍历methods,并转成大写、去重
methods = set(item.upper() for item in methods)
required_methods = set(getattr(view_func, "required_methods", ()))
if provide_automatic_options is None:
provide_automatic_options = getattr(
view_func, "provide_automatic_options", None
)
if provide_automatic_options is None:
if "OPTIONS" not in methods:
provide_automatic_options = True
required_methods.add("OPTIONS")
else:
provide_automatic_options = False
methods |= required_methods
rule = self.url_rule_class(rule, methods=methods, **options)
rule.provide_automatic_options = provide_automatic_options
self.url_map.add(rule) # 添加匹配规则
if view_func is not None:
old_func = self.view_functions.get(endpoint) # 默认self.view_functions={},所以old_func=None
if old_func is not None and old_func != view_func:
raise AssertionError(
"View function mapping is overwriting an "
"existing endpoint function: %s" % endpoint
)
self.view_functions[endpoint] = view_func # 将 endpoint 与 view_func 对应。{endpoint:view_func}
一つは、ソースコードを見ることができ、コメントを追加するコードの関連部分上記の無知ではありません。情報を取得します。
(1)の方法は、それが指定されていない場合、デフォルトのモードが取得され、ビューモード要求機能で定義されています
(2)メソッド送信パラメータが通過することができない文字列型であり、提供されるべきである:方法は=(「ポスト」)、パラメータは大文字と小文字を区別しない、すなわち、「ポスト」と「POST」を通過させることができるされています
(3)の値は、エンドポイント=「XXX」として、関数名エンドポイントに対応する:それはエイリアスインデックス関数を見た図に相当します。何のエンドポイントが存在しない場合、実行し_endpoint_from_view_func(view_func)
、エンドポイント=関数名
def _endpoint_from_view_func(view_func):
"""Internal helper that returns the default endpoint for a given
function. This always is the function name.
"""
assert view_func is not None, "expected view func if endpoint is not provided."
return view_func.__name__ # 返回的就是函数名
要約:
(1)ルーティングは、本質的にadd_url_rule機能を実行し、によってルーティング機能を追加することも可能ですapp.add_url_rule('/',endpoint='xxx',view_func=index)
(2)エンドポイント:エイリアスを指定するには、関数名を指定しません
(3)方法:ビュー機能を指定する要求、それが指定されていないデフォルトが取得する方法
(4)なurl_for:逆ルート解像度エイリアスを行います
from flask import Flask, request,redirect,url_for
app = Flask(__name__)
app.debug =True
# @app.route('/')
def index():
return 'dasdk'
app.add_url_rule('/',endpoint='xxx',view_func=index) # 用来绑定路由
@app.route('/login',methods=['post','get'])
def login():
url = url_for('xxx') # 反向路由解析,url此时指向index视图函数
return redirect(url)
if __name__ == '__main__':
app.run()