有谁知道如果我有两个这样的URL规则,为什么我不能覆盖现有的终结点函数?
app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["GET"])
追溯:
Traceback (most recent call last): File "demo.py", line 20, in <module> methods=["GET"]) File ".../python2.6/site-packages/flask/app.py", line 62, in wrapper_func return f(self, *args, **kwargs) File ".../python2.6/site-packages/flask/app.py", line 984, in add_url_rule 'existing endpoint function: %s' % endpoint) AssertionError: View function mapping is overwriting an existing endpoint function: main
你的视图名称即使指向相同的视图方法,也必须是唯一的。
app.add_url_rule('/', view_func=Main.as_view('main'), methods = ['GET']) app.add_url_rule('/<page>/', view_func=Main.as_view('page'), methods = ['GET'])
我在模块中有多个API函数并尝试用2个装饰器包装每个函数时,我也遇到了同样的问题:
@app.route("/path1") @exception_handler def func1(): pass @app.route("/path2") @exception_handler def func2(): pass
具体来说,这是由于尝试使用名称包装器注册了一些函数引起的:
def exception_handler(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: error_code = getattr(e, "code", 500) logger.exception("Service exception: %s", e) r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code}) return Response(r, status=error_code, mimetype='application/json') return wrapper
更改函数名称为我解决了这个问题(wrapper . name = func . name):
def exception_handler(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: error_code = getattr(e, "code", 500) logger.exception("Service exception: %s", e) r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code}) return Response(r, status=error_code, mimetype='application/json') # Renaming the function name: wrapper.__name__ = func.__name__ return wrapper
然后,装饰多个端点起作用。