Flask注册视图函数

那天莫名其妙出了个错。。就顺便看了看Flask路由

在flask存储路由函数是以函数名为键,函数对象为值

class Flask:
    def __init__(self, *args, **kwargs):
        #所有视图函数的注册将被放在字典。键是函数名,值是函数对象,函数名也用于生成URL。注册一个视图函数,用route装饰器。
        self.view_functions= {}

app.route装饰器注册视图函数

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函数

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'

@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

视图函数名重复

@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解决

@app.route('/s/', endpoint='h')
def a():
    return 'helloooo'

@app.route('/ss/')
def a():
    return 'ahahaha'

相关推荐