那天莫名其妙出了个错。。就顺便看了看Flask路由前端
在flask存储路由函数是以函数名为键,函数对象为值flask
class Flask: def __init__(self, *args, **kwargs): #全部视图函数的注册将被放在字典。键是函数名,值是函数对象,函数名也用于生成URL。注册一个视图函数,用route装饰器。 self.view_functions= {}
app.route装饰器注册视图函数app
def route(self, rule, **options): #用来给给定的URL注册视图函数的装饰器,也能够用add_url_rule函数来注册。endpoint关键字参数默认是视图函数的名字 def decorator(f): endpoint = options.pop('endpoint', None) #pop删除endpoint的值没有为None并返回它赋值给endpoint self.add_url_rule(rule, endpoint, f, **options) #调用add_url_rule函数 return f return decorator
add_url_rule函数ide
def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options): if endpoint is None: endpoint = _endpoint_from_view_func(view_func) #_endpoint_from_view_fun函数返回视图函数名view_fun.__name__ options['endpoint'] = endpoint #...... if view_func is not None: old_func = self.view_functions.get(endpoint) if old_func is not None and old_func != view_func: raise AssertionError('View function mapping is overwriting an ' 'existing endpoint function: %s' % endpoint) #old_func对象从储存视图函数的字典中取出,若是它不为空而且不等于视图函数那么就会报错视图函数覆盖当前端点函数,若是有同名函数能够经过修改endpoint值来避免这个错误。 self.view_functions[endpoint] = view_func #函数名做为键,函数对象做为值存储到view_functions中。
获取储存视图函数字典中的函数对象函数
from flask import Flask app = FLask(__name__) @app.route('/') def index(): return '<h1>视图函数:{} /endpoint:{}</h1>'.format(app.view_functions.get('index','None').__name__, app.view_functions.keys()) #FLask类中的view_functions字典储存了注册的视图函数名和视图函数对象。函数名为endpoint默认就是视图函数的名字,get方法得到视图函数对象,__name__过的函数名。这个字典的键就是endponit的值。 输出: endpoint:dict_keys(['static', 'index'])/视图函数:index
若是自定义endponit = 'hello'url
@app.route('/', endpoint='hello') def index(): return '<h1>endpoint:{}/视图函数:{}</h1>'.format(app.view_functions.keys(), app.view_functions.get('hello','None').__name__) #字典键值就是endponit值改成自定义的值来获取试图函数对象。 输出: endpoint:dict_keys(['static', 'hello'])/视图函数:index
视图函数名重复code
@app.route('/s/') def a(): return 'helloooo' @app.route('/ss/') def a(): return 'ahahaha' #AssertionError: View function mapping is overwriting an existing endpoint function: a
修改endpoint解决orm
@app.route('/s/', endpoint='h') def a(): return 'helloooo' @app.route('/ss/') def a(): return 'ahahaha'