AssertionError: View function mapping is overwriting an existing endpoint function: main

PythonFlask

Python Problem Overview


Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this

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:

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

Python Solutions


Solution 1 - Python

This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators:

  1. @app.route()
  2. My custom @exception_handler decorator

I got this same exception because I tried to wrap more than one function with those two decorators:

@app.route("/path1")
@exception_handler
def func1():
    pass

@app.route("/path2")
@exception_handler
def func2():
    pass

Specifically, it is caused by trying to register a few functions with the name wrapper:

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

Changing the name of the function solved it for me (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

Then, decorating more than one endpoint worked.

Solution 2 - Python

Your view names need to be unique even if they are pointing to the same view method.

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'])

Solution 3 - Python

For users that use @app.route it is better to use the key-argument endpoint rather then chaning the value of __name__ like Roei Bahumi stated. Taking his example will be:

@app.route("/path1", endpoint='func1')
@exception_handler
def func1():
    pass

@app.route("/path2", endpoint='func2')
@exception_handler
def func2():
    pass

Solution 4 - Python

Flask requires you to associate a single 'view function' with an 'endpoint'. You are calling Main.as_view('main') twice which creates two different functions (exactly the same functionality but different in memory signature). Short story, you should simply do

main_view_func = Main.as_view('main')

app.add_url_rule('/',
             view_func=main_view_func,
             methods=["GET"])

app.add_url_rule('/<page>/',
             view_func=main_view_func,
             methods=["GET"])

Solution 5 - Python

This can happen also when you have identical function names on different routes.

Solution 6 - Python

I would just like to add to this a more 'template' type solution.

def func_name(f):
    def wrap(*args, **kwargs):
        if condition:
            pass
        else:
            whatever you want
        return f(*args, **kwargs)
    wrap.__name__ = f.__name__
    return wrap

would just like to add a really interesting article "Demystifying Decorators" I found recently: https://sumit-ghosh.com/articles/demystifying-decorators-python/

Solution 7 - Python

Adding @wraps(f) above the wrapper function solved my issue.

def list_ownership(f):
    @wraps(f)
    def decorator(*args,**kwargs):
        return f(args,kwargs)
    return decorator

Solution 8 - Python

There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised.

See https://github.com/mitsuhiko/flask/issues/796

So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version.

The diff of that change is here: http://github.com/mitsuhiko/flask/commit/661ee54bc2bc1ea0763ac9c226f8e14bb0beb5b1

Solution 9 - Python

If you think you have unique endpoint names and still this error is given then probably you are facing issue. Same was the case with me.

This issue is with flask 0.10 in case you have same version then do following to get rid of this:

sudo pip uninstall flask
sudo pip install flask=0.9

Solution 10 - Python

Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps https://docs.python.org/2/library/functools.html

Solution 11 - Python

use flask 0.9 instead use the following commands sudo pip uninstall flask

sudo pip install flask==0.9

Solution 12 - Python

In case you are using flask on python notebook, you need to restart kernel everytime you make changes in code

Solution 13 - Python

This is issue for me was from an (breaking) update to flask-jwt-extended (version 4.x.x and up) used in a basic api I wrote a year ago and am now incorporating into a project.

@jwt_required to @jwt_required()

Solution 14 - Python

maybe something contains no difference

  1. check url
  2. check function name

Solution 15 - Python

I'm working on a similar problem and I managed to get rid of it by returning the wrapper funcion, which wasn't being done before:

def decorator_func(func_to_decorate):
    def wrapper_func():
        return func_to_decorate
    return wrapper_func     # I wasn't returning wrapper func!

Solution 16 - Python

I encountered the same AssertionError, but have not seen a solution here. In my case, I run a decorated function in a Jupyter cell twice, then the error was caused by running an endpoint function with the same name as an existing running endpoint function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKimmyView Question on Stackoverflow
Solution 1 - PythonRoei BahumiView Answer on Stackoverflow
Solution 2 - PythonMichael DavisView Answer on Stackoverflow
Solution 3 - PythonUri ShalitView Answer on Stackoverflow
Solution 4 - PythondtheodorView Answer on Stackoverflow
Solution 5 - PythonJosephView Answer on Stackoverflow
Solution 6 - PythonimbatmanView Answer on Stackoverflow
Solution 7 - PythonMatija ŽibernaView Answer on Stackoverflow
Solution 8 - PythonyassenView Answer on Stackoverflow
Solution 9 - PythonshrishindeView Answer on Stackoverflow
Solution 10 - PythonAndriy ShchudloView Answer on Stackoverflow
Solution 11 - PythonJoshua JohnsView Answer on Stackoverflow
Solution 12 - Pythonimok1948View Answer on Stackoverflow
Solution 13 - PythonpopandpeekView Answer on Stackoverflow
Solution 14 - PythonwangyonghengView Answer on Stackoverflow
Solution 15 - PythonKubinhaView Answer on Stackoverflow
Solution 16 - PythonLerner ZhangView Answer on Stackoverflow