源代码如下, 启动报错

from flask import Flask

# 实例化一个Flask对象
app = Flask(__name__)
# 打印默认配置信息

# 引入开发环境的配置
app.config.from_object('settings.DEV')


# 引入生产环境的配置
# app.config.from_object('settings.Pro')



def validate(func):
    """
    定义一个装饰器(啥事都没有干)

    :param func:
    :return:
    """

    def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return inner


@app.route('/index1', methods=['GET', 'POST'])
@validate
def index1():
    print('index1')


@app.route('/index2', methods=['GET', 'POST'])
@validate
def index2():
    print('index2')


if __name__ == '__main__':
    app.run(threaded=True)

报错信息如下:

Traceback (most recent call last):
  File "E:/ws/python/LearnFlask/app5.py", line 37, in <module>
    @validate
  File "C:\Users\zhengqinfeng\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1314, in decorator
    self.add_url_rule(rule, endpoint, f, **options)
  File "C:\Users\zhengqinfeng\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 98, in wrapper_func
    return f(self, *args, **kwargs)
  File "C:\Users\zhengqinfeng\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1283, in add_url_rule
    "existing endpoint function: %s" % endpoint
AssertionError: View function mapping is overwriting an existing endpoint function: inner

 

报错原因: index1和index2添加了validate装饰器之后,它们的函数名称都变成了inner,同名了, 这样router建立路由关系时,就会报错。

解决方法:

第一种方式:

  添加endpoint

 

第二种方式: 

  使用functools工具类

 

import functools
def validate(func):
    """
    定义一个装饰器(啥事都没有干)

    :param func:
    :return:
    """
    @functools.wraps(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return inner

 

如此,便可解决报错问题

 

posted on 2020-02-13 11:14  显示账号  阅读(554)  评论(0编辑  收藏  举报