Python Forum
AssertionError: View function mapping is overwriting an existing endpoint function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
AssertionError: View function mapping is overwriting an existing endpoint function
#1
Tried for a while to fix this but nothing helped, I don't know what's throwing this issue.

My views.py

"""
Routes and views for the flask application.
"""

import datetime
from datetime import datetime
import get

from flask import render_template, redirect, request

from FlaskWebProject1 import app
from FlaskWebProject1.models import PollNotFound
from FlaskWebProject1.models.factory import create_repository
from FlaskWebProject1.settings import REPOSITORY_NAME, REPOSITORY_SETTINGS

import numpy as np
import matplotlib.pyplot as plt

import pandas as pd
import json
import requests

import io 
import base64

from flask import Flask, render_template, flash, request
from wtforms import Form, BooleanField, StringField, PasswordField, validators
from wtforms import TextField, TextAreaField, SubmitField
from wtforms import ValidationError

from FlaskWebProject1.models.objects import RegistrationForm 
from FlaskWebProject1.models.objects import LoginForm 
from FlaskWebProject1.models.objects import SearchParameters 

repository = create_repository(REPOSITORY_NAME, REPOSITORY_SETTINGS)

# -------------------------------------------------------
# transform a picture to a memory represenation of the image
# -------------------------------------------------------
def fig_to_base64(fig):
    img = io.BytesIO()
    fig.savefig(img, format='png',
                bbox_inches='tight')
    img.seek(0)
    return base64.b64encode(img.getvalue())

# -------------------------------------------------------
# return boolean if username (paramter) is in the Users DB
# -------------------------------------------------------
def IsUserExist(UserName):
    # Load the database of users
    df = repository.OpenUsersDB()
    df = df.set_index('username')
    return (UserName in df.index.values)

# -------------------------------------------------------
# return boolean if username/password pair is in the DB
# -------------------------------------------------------
def IsLoginGood(UserName, Password):
    # Load the database of users
    df = repository.OpenUsersDB()
    df=df.reset_index()
    selection = [UserName]
    df = df[pd.DataFrame(df.username.tolist()).isin(selection).any(1)]

    df = df.set_index('password')
    return (Password in df.index.values)

# -------------------------------------------------------
# Add a new user to the DB
# -------------------------------------------------------
def AddNewUser(User):
    # Load the database of users
    df = repository.OpenUsersDB()
    dfNew = pd.DataFrame([[User.username.data, User.password.data,User.email.data,User.phone.data,User.firstname.data,User.lastname.data]], columns=['username', 'password', 'email', 'phone', 'firstname', 'lastname'])
    dfComplete = df.append(dfNew, ignore_index=True)
    repository.WriteToFile_users(dfComplete)

# -------------------------------------------------------
# Page routing - position of the home page
# -------------------------------------------------------
@app.route('/')
@app.route('/home')
def home():
    """Renders the home page, with a list of all polls."""
    return render_template(
        'index.html',
        title='Home',
        year=datetime.now().year,
        month=datetime.now().month,
        day=datetime.now().day,
        hour=datetime.now().hour,
        minute=datetime.now().minute,
        polls=repository.get_polls(),
    )

# -------------------------------------------------------
# Page routing - position of the about page
# -------------------------------------------------------
@app.route('/about')
def about():
    """Renders the about page."""
    return render_template(
        'about.html',
        title='About',
        year=datetime.now().year,
        month=datetime.now().month,
        day=datetime.now().day,
        hour=datetime.now().hour,
        minute=datetime.now().minute,
        repository_name=repository.name,
    )

# -------------------------------------------------------
# Page routing - position of the contact page
# -------------------------------------------------------
@app.route('/contact')
def contact():
    """Renders the contact page."""
    return render_template(
        'contact.html',
        title='Contact',
        year=datetime.now().year,
        month=datetime.now().month,
        day=datetime.now().day,
        hour=datetime.now().hour,
        minute=datetime.now().minute,
    )

# -------------------------------------------------------
# Register new user page
# -------------------------------------------------------
@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User(form.username.data, form.email.data,
                    form.password.data)
        db_session.add(user)
        flash('Thanks for registering')
        return redirect(url_for('/home'))
    else:
        return render_template(
            'register.html', 
            year=datetime.now().year,
            month=datetime.now().month,
            day=datetime.now().day,
            hour=datetime.now().hour,
            minute=datetime.now().minute,
            form=form
         )

# -------------------------------------------------------
# Login page
# This page is the filter before the data analysis
# -------------------------------------------------------
@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)

    if (request.method == 'POST' and form.validate()):
        if (IsLoginGood(form.username.data, form.password.data)):
            return redirect('GetParameters')
        else:
            flash('Error in - Username and password')
   
    return render_template(
        'login.html', 
        form=form, 
        title='Login to data analysis',
        year=datetime.now().year,
        repository_name='Pandas',
        )
# -------------------------------------------------------
# When a user was qualified o enter the DB page
# he needs to enter some parameters to set the requested
# query
# -------------------------------------------------------
@app.route('/GetParameters', methods=['GET', 'POST'])
def GetParameters():
    form = SearchParameters(request.form)
 
    if (request.method == 'POST' and form.validate()):
            return pandas(form)
 
    return render_template(
            'GetParameters.html', 
            form=form, 
            title='Enter parameters for data analysis',
            year=datetime.now().year,
            repository_name='Pandas',
            )
  
# -------------------------------------------------------
# The data analysis page according to the entered parameters
# Get parameters that the user entered
# -------------------------------------------------------
@app.route('/pandas/<form>')
def pandas(form):
    #choosedatabase = form.choosedatabase.data
    #startdate = form.startdate.data
    #form = SearchParameters(self.request.POST)

    if (form!='None'):
        form = SearchParameters(request.form)

        DBPath=form.choosedatabase.data
        FromDate = form.startdate.data
        #DBPath='https://data.gov.il/api/action/datastore_search?resource_id=1cf76fb6-1813-40b8-b13f-91ecc1384994&limit=1000'
        #FromDate = "1/1/2019"
    else:
        DBPath='https://data.gov.il/api/action/datastore_search?resource_id=1cf76fb6-1813-40b8-b13f-91ecc1384994&limit=1000'
        FromDate = "1/1/2019"
    r = requests.get(DBPath)
    x = r.json()
    #y = str(type(x))
    df = pd.DataFrame.from_dict(x["result"]["records"])
    db_table = df.head(5).to_html(escape=False)

    fig, ax = plt.subplots()
    df['_id'].hist()
    
    encoded = fig_to_base64(fig)
    plot_img = '<img src="data:image/png;base64, {}">'.format(encoded.decode('utf-8'))

    return render_template(
        'pandas.html',
        title='Pandas',
        year=datetime.now().year,
        repository_name='Pandas',
        db_table=db_table,
        plot_img=plot_img,
    )
My __init___.py

"""
The flask application package.
"""

from flask import Flask

app = Flask(__name__)


import FlaskWebProject1.views

def _load_users():
    users_db = path.join(path.dirname(_file_), '..\\static\\db\\users.json')

    try:
        with open(users_db, 'r') as userfile:
            s = json.load(userfile)
            x = json.load(s)

            df = pd.DataFrame.from_dict(x)

    except:
        Data = {'username': ['netalevy', 'admin'],
                'password': ['netalevy', 'admin1234'],
                'email': ['[email protected]', '[email protected]'],
                'phone': ['054-3333475', '054-3333475'],
                'firstname': ['Neta', 'Teacher'],
                'lastname': ['Levy', 'Tichonet']
                }
        df = pd.DataFrame(Data, collums=['username', 'password', 'email', 'phone', 'firstname', 'lastname']) 
    finally:
        return df
I have been looking for days how to fix this... Please help me.

Thanks in advance.

And sorry for not pointing out that the full error is:

Error:
Traceback (most recent call last): File "C:\Users\User\source\repos\FlaskWebProject1\FlaskWebProject1\FlaskWebProject1\views.py", line 83, in <module> @app.route('/home') File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\flask\app.py", line 1250, in decorator self.add_url_rule(rule, endpoint, f, **options) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\flask\app.py", line 66, in wrapper_func return f(self, *args, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\flask\app.py", line 1221, in add_url_rule 'existing endpoint function: %s' % endpoint) AssertionError: View function mapping is overwriting an existing endpoint function: home Press any key to continue . . .
So the function that throws this error is home.
Reply
#2
Without looking into you code, I guess you,ve decorated the two different functions with app.route. Rename one function from home to home2 e.g.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
(Apr-17-2019, 11:08 AM)DeaD_EyE Wrote: Withou looking into you code, I guess you,ve decorated the two different functions with app.toute. Rename one function from home teo home2 e.g.
Sorry I didn't quite understand you but if I did understand I can assure you that there is only one function called home.
Reply
#4
It seems not the case. Answering by smartphone is not easy. Looking later on my Pc.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
(Apr-17-2019, 11:16 AM)DeaD_EyE Wrote: It seems not the case. Answering by smartphone is not easy. Looking later on my Pc.
Ok thank you very much! I have been looking for a person to help me debug this for a while now, thank you so much!
Reply
#6
Please edit your original post. Put the code into code tags.
Otherwise there is no indentation and no line numbers.


[python]
your code
[/python]
I think the problem is that you try to reuse the app object in the other module.
You should look for blueprints:

Example structure:
web
├── app.py
├── __init__.py
├── __main__.py
├── pages.py
└── __pycache__
    ├── app.cpython-37.pyc
    ├── __main__.cpython-37.pyc
    └── pages.cpython-37.pyc
app.py:
from flask import Flask
import pages

app = Flask(__name__)
app.register_blueprint(pages.bp)
app.run()
pages.py
from flask import Blueprint

# this is the blueprint object which
# have to registered with app
bp = Blueprint('main_page', __name__, template_folder='templates')


@bp.route('/')
@bp.route('/test123')
def index():
    return 'index'


@bp.route('/auth')
def auth():
   return 'auth'


@bp.route('/info')
def info():
    return 'info'
Additional ressources:
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
(Apr-17-2019, 10:48 AM)Zhavi221 Wrote: Tried for a while to fix this but nothing helped, I don't know what's throwing this issue. My views.py """ Routes and views for the flask application. """ import datetime from datetime import datetime import get from flask import render_template, redirect, request from FlaskWebProject1 import app from FlaskWebProject1.models import PollNotFound from FlaskWebProject1.models.factory import create_repository from FlaskWebProject1.settings import REPOSITORY_NAME, REPOSITORY_SETTINGS import numpy as np import matplotlib.pyplot as plt import pandas as pd import json import requests import io import base64 from flask import Flask, render_template, flash, request from wtforms import Form, BooleanField, StringField, PasswordField, validators from wtforms import TextField, TextAreaField, SubmitField from wtforms import ValidationError from FlaskWebProject1.models.objects import RegistrationForm from FlaskWebProject1.models.objects import LoginForm from FlaskWebProject1.models.objects import SearchParameters repository = create_repository(REPOSITORY_NAME, REPOSITORY_SETTINGS) # ------------------------------------------------------- # transform a picture to a memory represenation of the image # ------------------------------------------------------- def fig_to_base64(fig): img = io.BytesIO() fig.savefig(img, format='png', bbox_inches='tight') img.seek(0) return base64.b64encode(img.getvalue()) # ------------------------------------------------------- # return boolean if username (paramter) is in the Users DB # ------------------------------------------------------- def IsUserExist(UserName): # Load the database of users df = repository.OpenUsersDB() df = df.set_index('username') return (UserName in df.index.values) # ------------------------------------------------------- # return boolean if username/password pair is in the DB # ------------------------------------------------------- def IsLoginGood(UserName, Password): # Load the database of users df = repository.OpenUsersDB() df=df.reset_index() selection = [UserName] df = df[pd.DataFrame(df.username.tolist()).isin(selection).any(1)] df = df.set_index('password') return (Password in df.index.values) # ------------------------------------------------------- # Add a new user to the DB # ------------------------------------------------------- def AddNewUser(User): # Load the database of users df = repository.OpenUsersDB() dfNew = pd.DataFrame([[User.username.data, User.password.data,User.email.data,User.phone.data,User.firstname.data,User.lastname.data]], columns=['username', 'password', 'email', 'phone', 'firstname', 'lastname']) dfComplete = df.append(dfNew, ignore_index=True) repository.WriteToFile_users(dfComplete) # ------------------------------------------------------- # Page routing - position of the home page # ------------------------------------------------------- @app.route('/') @app.route('/home') def home(): """Renders the home page, with a list of all polls.""" return render_template( 'index.html', title='Home', year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, hour=datetime.now().hour, minute=datetime.now().minute, polls=repository.get_polls(), ) # ------------------------------------------------------- # Page routing - position of the about page # ------------------------------------------------------- @app.route('/about') def about(): """Renders the about page.""" return render_template( 'about.html', title='About', year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, hour=datetime.now().hour, minute=datetime.now().minute, repository_name=repository.name, ) # ------------------------------------------------------- # Page routing - position of the contact page # ------------------------------------------------------- @app.route('/contact') def contact(): """Renders the contact page.""" return render_template( 'contact.html', title='Contact', year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, hour=datetime.now().hour, minute=datetime.now().minute, ) # ------------------------------------------------------- # Register new user page # ------------------------------------------------------- @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): user = User(form.username.data, form.email.data, form.password.data) db_session.add(user) flash('Thanks for registering') return redirect(url_for('/home')) else: return render_template( 'register.html', year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, hour=datetime.now().hour, minute=datetime.now().minute, form=form ) # ------------------------------------------------------- # Login page # This page is the filter before the data analysis # ------------------------------------------------------- @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm(request.form) if (request.method == 'POST' and form.validate()): if (IsLoginGood(form.username.data, form.password.data)): return redirect('GetParameters') else: flash('Error in - Username and password') return render_template( 'login.html', form=form, title='Login to data analysis', year=datetime.now().year, repository_name='Pandas', ) # ------------------------------------------------------- # When a user was qualified o enter the DB page # he needs to enter some parameters to set the requested # query # ------------------------------------------------------- @app.route('/GetParameters', methods=['GET', 'POST']) def GetParameters(): form = SearchParameters(request.form) if (request.method == 'POST' and form.validate()): return pandas(form) return render_template( 'GetParameters.html', form=form, title='Enter parameters for data analysis', year=datetime.now().year, repository_name='Pandas', ) # ------------------------------------------------------- # The data analysis page according to the entered parameters # Get parameters that the user entered # ------------------------------------------------------- @app.route('/pandas/<form>') def pandas(form): #choosedatabase = form.choosedatabase.data #startdate = form.startdate.data #form = SearchParameters(self.request.POST) if (form!='None'): form = SearchParameters(request.form) DBPath=form.choosedatabase.data FromDate = form.startdate.data #DBPath='https://data.gov.il/api/action/datastore_search?resource_id=1cf76fb6-1813-40b8-b13f-91ecc1384994&limit=1000' #FromDate = "1/1/2019" else: DBPath='https://data.gov.il/api/action/datastore_search?resource_id=1cf76fb6-1813-40b8-b13f-91ecc1384994&limit=1000' FromDate = "1/1/2019" r = requests.get(DBPath) x = r.json() #y = str(type(x)) df = pd.DataFrame.from_dict(x["result"]["records"]) db_table = df.head(5).to_html(escape=False) fig, ax = plt.subplots() df['_id'].hist() encoded = fig_to_base64(fig) plot_img = '<img src="data:image/png;base64, {}">'.format(encoded.decode('utf-8')) return render_template( 'pandas.html', title='Pandas', year=datetime.now().year, repository_name='Pandas', db_table=db_table, plot_img=plot_img, ) My __init___.py """ The flask application package. """ from flask import Flask app = Flask(__name__) import FlaskWebProject1.views def _load_users(): users_db = path.join(path.dirname(_file_), '..\\static\\db\\users.json') try: with open(users_db, 'r') as userfile: s = json.load(userfile) x = json.load(s) df = pd.DataFrame.from_dict(x) except: Data = {'username': ['netalevy', 'admin'], 'password': ['netalevy', 'admin1234'], 'email': ['[email protected]', '[email protected]'], 'phone': ['054-3333475', '054-3333475'], 'firstname': ['Neta', 'Teacher'], 'lastname': ['Levy', 'Tichonet'] } df = pd.DataFrame(Data, collums=['username', 'password', 'email', 'phone', 'firstname', 'lastname']) finally: return df I have been looking for days how to fix this... Please help me. Thanks in advance.
And sorry for not pointing out that the full error is:
Error:
Traceback (most recent call last): File "C:\Users\User\source\repos\FlaskWebProject1\FlaskWebProject1\FlaskWebProject1\views.py", line 83, in <module> @app.route('/home') File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\flask\app.py", line 1250, in decorator self.add_url_rule(rule, endpoint, f, **options) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\flask\app.py", line 66, in wrapper_func return f(self, *args, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\flask\app.py", line 1221, in add_url_rule 'existing endpoint function: %s' % endpoint) AssertionError: View function mapping is overwriting an existing endpoint function: home Press any key to continue . . .
So the function that throws this error is home.
Reply
#8
(Apr-17-2019, 12:52 PM)DeaD_EyE Wrote: Please edit your original post. Put the code into code tags. Otherwise there is no indentation and no line numbers.
 [python] your code [/python] 
I think the problem is that you try to reuse the app object in the other module. You should look for blueprints: Example structure:
 web ├── app.py ├── __init__.py ├── __main__.py ├── pages.py └── __pycache__ ├── app.cpython-37.pyc ├── __main__.cpython-37.pyc └── pages.cpython-37.pyc 
app.py:
 from flask import Flask import pages app = Flask(__name__) app.register_blueprint(pages.bp) app.run() 
pages.py
 from flask import Blueprint # this is the blueprint object which # have to registered with app bp = Blueprint('main_page', __name__, template_folder='templates') @bp.route('/') @bp.route('/test123') def index(): return 'index' @bp.route('/auth') def auth(): return 'auth' @bp.route('/info') def info(): return 'info' 
Additional ressources:
I am not an expert, I didn't really understand. And how do I edit the post?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  The function of double underscore back and front in a class function name? Pedroski55 9 563 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  Mapping a value to an interval JazonKuer 12 1,846 Mar-17-2023, 07:59 PM
Last Post: Gribouillis
  AssertionError when trying the sys module in python BliepMonster 10 2,044 Nov-21-2022, 08:43 PM
Last Post: BliepMonster
  access is denied error 5 for network drive mapping ? ahmedbarbary 2 1,731 Aug-17-2022, 10:09 PM
Last Post: ahmedbarbary
  Requests Session Overwriting and cookie jar muzikman 0 1,267 Dec-13-2021, 02:22 PM
Last Post: muzikman
  Exit function from nested function based on user input Turtle 5 2,858 Oct-10-2021, 12:55 AM
Last Post: Turtle
  Mapping a range ebolisa 5 3,415 Jun-12-2021, 11:17 PM
Last Post: ebolisa
Question Stopping a parent function from a nested function? wallgraffiti 1 3,621 May-02-2021, 12:21 PM
Last Post: Gribouillis
Question exiting the outer function from the inner function banidjamali 3 3,466 Feb-27-2021, 09:47 AM
Last Post: banidjamali
  Passing argument from top-level function to embedded function JaneTan 2 2,206 Oct-15-2020, 03:50 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020