Python Forum
View function mapping is overwriting an existing endpoint function: index
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
View function mapping is overwriting an existing endpoint function: index
#1
please give a runnable sample of your code with the full error text or a clear description of the problem
This is the error am having:
Traceback (most recent call last):
File "manage.py", line 3, in <module>
from thermos import app, db
File "/Users/MAC/dev/thermos/thermos/__init__.py", line 16, in <module>
import views
File "/Users/MAC/dev/thermos/thermos/views.py", line 10, in <module>
@app.route('/index')
File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1080, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func
return f(self, *args, **kwargs)
File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1051, in add_url_rule
'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: index

This is my __init__.py:
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY']= '\xd4\xdf\xac\xf1\x1f\xcbGt\xd0,\xbb\xd9\x02\xaf/+n\x08\x13t\x9fd\x12g'
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///'+ os.path.join(basedir,'thermos.db')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
app.config['DEBUG']= True
db = SQLAlchemy(app)

import models
import views
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY']= 'its_a_secret'
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///'+ os.path.join(basedir,'thermos.db')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
app.config['DEBUG']= True
db = SQLAlchemy(app)

import models
import views

and my manaage.py is this:

#! /usr/bin/env python

from thermos import app, db
from thermos.models import User
from flask_script import Manager, prompt_bool

from thermos import db
from models import User

manager = Manager(app)

@manager.command
def initdb():
db.create_all()
db.session.add(User(username="olatunji",email="olatunji. [email protected]"))
db.session.add(User(username="Samuel",email="abiodun@Sam [email protected]"))
db.session.commit()
print 'Initialized the database'

@manager.command
def dropdb():
if prompt_bool(
"Are you sure you want to lose all your data"):
db.drop_all()
print 'Dropped the database'

if __name__ == '__main__':
manager.run()

and my model.py is this:
from datetime import datetime

from sqlalchemy import desc

from thermos import db

class Bookmark(db.Model):
id = db.Column(db.Integer,primary_key=True)
url = db.Column(db.Text,nullable=False)
date = db.Column(db.DateTime,default=datetime.utcnow)
description = db.Column(db.String(300))
user_id = db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)

@staticmethod
def newest(num):
return Bookmark.query.order_by(desc(Bookmark.date)).limit(num)

def __repr__(self):
return "<Bookmark '{}': '{}'>".format(self.description,self.url)

class User(db.Model):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(80),unique=True)
email = db.Column(db.String(120),unique=True)
bookmarks = db.relationship('Bookmark',backref='user',lazy='dynamic')

def __repr__(self):
return "<User '{}'>".format(self.username)
how can I correct this error?
Reply
#2
Quote:
Error:
AssertionError: View function mapping is overwriting an existing endpoint function: index

Do you have more than one function routed to "/" in your views?
Reply
#3
Error:
(most recent call last): File "manage.py", line 3, in <module> from thermos import app, db File "/Users/MAC/dev/thermos/thermos/__init__.py", line 16, in <module> import views File "/Users/MAC/dev/thermos/thermos/views.py", line 10, in <module> @app.route('/index') File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1080, in decorator self.add_url_rule(rule, endpoint, f, **options) File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func return f(self, *args, **kwargs) File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1051, in add_url_rule 'existing endpoint function: %s' % endpoint) AssertionError: View function mapping is overwriting an existing endpoint function: index

This is my __init__.py:

import os
 
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
 
basedir = os.path.abspath(os.path.dirname(__file__))
 
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///'+ os.path.join(basedir,'thermos.db')
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
app.config['DEBUG']= True
db = SQLAlchemy(app)

This is my view.py:

from flask import render_template, flash, redirect, url_for
 
from thermos import app,db
from forms import BookmarkForm
from models import User, Bookmark
 
def logged_in_user():
    return user.query.filter_by(username='olatunji').first()
 
@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html',new_bookmarks=models.Bookmark.newest(5))
 
@app.route('/add',methods=['GET','POST'])
def add():
    form = BookmarkForm()
    if form.validate_on_submit():
        url = form.url.data
        description = form.description.data
        bm = models.Bookmark(url=url, description=description)
        bm = Bookmark(user=logged_in_user(),url=url,description=description)
        db.session.add(bm)
        db.session.commit()
        flash("stored '{}'".format(description))
        return redirect(url_for('index'))
    return render_template('add.html',form=form)
 
if __name__ == "__main__":
    app.run(debug=True)
I need help on this.
Reply
#4
Quote:
@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html',new_bookmarks=models.Bookmark.newest(5))

Try getting rid of one of those routes.  / and /index are the same thing, which could be throwing the assertion.
Reply
#5
Quote:Try getting rid of one of those routes. / and /index are the same thing, which could be throwing the assertion.
I have removed one of the routes but the error is still been raised.
Reply
#6
the problem is that in thermos app you also have route index and the traceback is pretty clear about that

Error:
File "manage.py", line 3, in <module> from thermos import app, db File "/Users/MAC/dev/thermos/thermos/__init__.py", line 16, in <module> import views File "/Users/MAC/dev/thermos/thermos/views.py", line 10, in <module> @app.route('/index') File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1080, in decorator self.add_url_rule(rule, endpoint, f, **options) File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func return f(self, *args, **kwargs) File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1051, in add_url_rule 'existing endpoint function: %s' % endpoint) [error]AssertionError: View function mapping is overwriting an existing endpoint function: index
note the chain of imports: from thermos import app ->__init__.py -> views.py and there on line 10 you have @app.route('/index')
Reply
#7
Quote:note the chain of imports: from thermos import app ->__init__.py -> views.py and there on line 10 you have @app.route('/index')
.

How do I resolve this to avoid this cyclic import because I noticed when I move manage.py into the thermos package it ran.Is there a way to make manage.py stand alone and avoid cyclic import problem as well.Thats what am trying to do.Any suggestion will be appreciated.
Reply
#8
Please repost your original post in code tags as well as provide info on your project structure
at the moment it look like you use from thermos import app,db everywhere
Reply
#9
Quote:This is the project structure
Users-MacBook-Pro:thermos MAC$ ls -R
README.rst manage.py thermos

./thermos:
__init__.py forms.py models.py static thermos.db views.py
__init__.pyc forms.pyc models.pyc templates thermos.pyc views.pyc

./thermos/static:
css img js

./thermos/static/css:
main.css normalize.css normalize.min.css

./thermos/static/img:

./thermos/static/js:
main.js vendor

./thermos/static/js/vendor:
jquery-1.11.2.min.js modernizr-2.8.3-respond-1.4.2.min.js

./thermos/templates:
404.html add.html base.html form_macros.html index.html


Quote:
This is the __init__.py:
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'thermos.db')
app.config['DEBUG'] = True
db = SQLAlchemy(app)

import models
import views
Quote:This is the views.py:

from flask import render_template, flash, redirect, url_for, abort

from thermos import app, db
from forms import BookmarkForm
from models import User, Bookmark

# Fake login
def logged_in_user():
    return User.query.filter_by(username='olatunji').first()

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html', new_bookmarks=Bookmark.newest(5))


@app.route('/add', methods=['GET', 'POST'])
def add():
    form = BookmarkForm()
    if form.validate_on_submit():
        url = form.url.data
        description = form.description.data
        bm = Bookmark(user=logged_in_user(), url=url, description=description)
        db.session.add(bm)
        db.session.commit()
        flash("Stored '{}'".format(description))
        return redirect(url_for('index'))
    return render_template('add.html', form=form)


@app.route('/user/<username>')
def user(username):

    user = User.query.filter_by(username=username).first_or_404()
    return render_template('user.html', user=user)


@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def page_not_found(e):
    return render_template('500.html'), 500
Quote:This is the manage.py:
#! /usr/bin/env python

from thermos import app,db
from thermos.models import User
from flask_script import Manager, prompt_bool

manager = Manager(app)

@manager.command
def initdb():
    db.create_all()
    db.session.add(User(username="olatunji",email="olatunji.    [email protected]"))
    db.session.add(User(username="Samuel",email="abiodun@sam    [email protected]"))
    db.session.commit()
    print 'Initialized the database'

@manager.command
def dropdb():
    if prompt_bool(
        "Are you sure you want to lose all your data"):
        db.drop_all()
        print 'Dropped the database'
        
if __name__ == '__main__':
    manager.run()
Quote:This is form.py:
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.fields.html5 import URLField
from wtforms.validators import DataRequired,url

class BookmarkForm(FlaskForm):
    url = URLField('The URL for your bookmark:',validators=[DataRequired(),url()])
    description = StringField('Add an optional description')

    def validate(self):
        if not self.url.data.startswith("http://") or\
            self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data
        
        if not FlaskForm.validate(self):
            return False
        
        if not self.description.data:
            self.description.data = self.url.data
        return True
Reply
#10
Error:
File "manage.py", line 3, in <module> from thermos import app, db File "/Users/MAC/dev/thermos/thermos/__init__.py", line 16, in <module> import views File "/Users/MAC/dev/thermos/thermos/views.py", line 10, in <module> @app.route('/index') File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1080, in decorator self.add_url_rule(rule, endpoint, f, **options) File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 64, in wrapper_func return f(self, *args, **kwargs) File "/Users/MAC/.envs/thermos/lib/python2.7/site-packages/flask/app.py", line 1051, in add_url_rule 'existing endpoint function: %s' % endpoint) [error]AssertionError: View function mapping is overwriting an existing endpoint function: index
note the chain of imports: from thermos import app ->__init__.py -> views.py and there on line 10 you have @app.route('/index')
[/quote]

(Oct-06-2017, 06:15 AM)buran Wrote: Please repost your original post in code tags as well as provide info on your project structure
at the moment it look like you use from thermos import app,db everywhere
How can I do away with this error?
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 644 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  Variable for the value element in the index function?? Learner1 8 633 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Mapping a value to an interval JazonKuer 12 1,939 Mar-17-2023, 07:59 PM
Last Post: Gribouillis
  Index Function not recognized in Python 3 Peter_B_23 1 1,205 Jan-08-2023, 04:52 AM
Last Post: deanhystad
  access is denied error 5 for network drive mapping ? ahmedbarbary 2 1,786 Aug-17-2022, 10:09 PM
Last Post: ahmedbarbary
  Requests Session Overwriting and cookie jar muzikman 0 1,291 Dec-13-2021, 02:22 PM
Last Post: muzikman
  Exit function from nested function based on user input Turtle 5 2,896 Oct-10-2021, 12:55 AM
Last Post: Turtle
  Mapping a range ebolisa 5 3,483 Jun-12-2021, 11:17 PM
Last Post: ebolisa
Question Stopping a parent function from a nested function? wallgraffiti 1 3,669 May-02-2021, 12:21 PM
Last Post: Gribouillis
Question exiting the outer function from the inner function banidjamali 3 3,522 Feb-27-2021, 09:47 AM
Last Post: banidjamali

Forum Jump:

User Panel Messages

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