Flask注册视图函数

22次阅读

共计 1986 个字符,预计需要花费 5 分钟才能阅读完成。

那天莫名其妙出了个错。。就顺便看了看 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'


正文完
 0