AssertionError: View function mapping is overwriting an existing endpoint function: - python

I am creating an app with python and flask. I am getting the following error:
Traceback (most recent call last):
File "C:\Users\Albert\PycharmProjects\Carro\views_trips.py", line 10, in <module>
def index():
File "C:\Users\Albert\PycharmProjects\Carro\venv\lib\site-packages\flask\scaffold.py", line 439, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "C:\Users\Albert\PycharmProjects\Carro\venv\lib\site-packages\flask\scaffold.py", line 57, in wrapper_func
return f(self, *args, **kwargs)
File "C:\Users\Albert\PycharmProjects\Carro\venv\lib\site-packages\flask\app.py", line 1090, in add_url_rule
raise AssertionError(
AssertionError: View function mapping is overwriting an existing endpoint function: index
I have only one route.
from flask import render_template, request, redirect, session, flash, url_for, send_from_directory
from app import app
from models import Trips, Users, Cars, db
import time
from helpers import *
from flask_bcrypt import check_password_hash
#app.route('/')
def index():
nickname = 'Bertimaz'
trip = Trips.query.filter_by(user_nickname=nickname).order_by(Trips.initialTime.desc()).first()
user = Users.query.filter_by(nickname='Bertimaz') # não ta achando usuario
print(user.name)
car = Cars.query.filter_by(plate=trip.car_plate)
return render_template('home.html', titulo='Viagens', trip=trip, user=user, car=car)
It was able to run it before I started implementing my SQL alchemy models and I tried changing the index function name

Instead of running the file with the routes instead of the correct script below:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
from views_trips import *
from views_user import *
if __name__ == '__main__':
app.run(debug=True)

In your init.py, import the Falsk app and assign the value to that app.
from flask import **app**, Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from app.config import Config
**app = Flask(__name__)
app.config.from_object(Config)**
# DB
db = SQLAlchemy(app)
migrate = Migrate(app, db)
After you have these above entries, you can import the app as
from app import app
NOTE: Do not import the app in multiple py files.

Related

TypeError: Blueprint.__init__() got an unexpected keyword argument 'template_folder'

This is what my directory looks like
p/
student/
template/
student/
index.html/
views.py/
__init__.py/
app.py/
this is what my app.py file looks like
from flask import Flask, render_template
from p import app
#app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run()
__init__.py file
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] =
"postgresql://postgres:1234#localhost/studentRegDB"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
Migrate(app, db)
from p.student.views import student_blueprints
app.register_blueprint(student_blueprints, url_prefix='/student')
views.py file
from flask import Flask, request
import psycopg2
from p import db
from p.student.forms import studentform
from p.student.models import Student
from flask import Flask, render_template, url_for,redirect
from flask_blueprint import Blueprint
student_blueprints = Blueprint('student', __name__, template_folder='student')
#student_blueprints.route("/add", methods=["GET", "POST"])
def addstudent():
form = studentform()
if form.validate_on_submit():
name = request.form['name']
course = request.form['course']
new_student = Student(name,course)
db.session.add(new_student)
db.session.commit()
return redirect(url_for("success.html"))
return render_template("student.html", form=form)
when run the code i get the following error
student_blueprints = Blueprint('student', name, template_folder='student')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Blueprint.init() got an unexpected keyword argument 'template_folder'
thank you for your help
You have to be very careful with names. The package flask_blueprint is unrelated to the flask blueprints you get from from flask import Blueprint, and has completely different parameters.
I suggest you pip uninstall flask-blueprint, and change your code to
from flask import Blueprint

Flask-restful AttributeError: type object 'Project' has no attribute 'as_view'

So im still learning about the structure in flask it seems flask give a too much flexibilty which is kinda confusing for me to decide, so im trying to add my Resource class to the API with the current structure
api
/__init__.py
/project.py
models
/project_management.py
configs.py
configs.json
run.py
but it return error when running
AttributeError: type object 'Project' has no attribute 'as_view'
Traceback (most recent call last):
File "e:\project-py\run.py", line 6, in
from api import * File "e:\project-py\api_init_.py", line 9, in
from .project import * File "e:\project-py\api\project.py", line 6, in
#api.add_resource(Project, '/v1/project') File "C:\Users\rokie\Anaconda3\envs\py39-rest-flask\lib\site-packages\flask_restful_init_.py",
line 391, in add_resource
self.register_view(self.app, resource, *urls, **kwargs) File "C:\Users\rokie\Anaconda3\envs\py39-rest-flask\lib\site-packages\flask_restful_init.py",
line 431, in _register_view
resource_func = self.output(resource.as_view(endpoint, *resource_class_args, AttributeError: type object 'Project' has no attribute 'as_view'
My run.py
from functools import wraps
from flask import Flask, session, g, render_template, flash
# from flask_cors import CORS, cross_origin
from flask_wtf.csrf import CSRFProtect
from pages import *
from api import *
from config import create_app
app = create_app()
app.app_context().push()
# app.register_blueprint(pages)
app.register_blueprint(api, url_prefix='/api')
# app.secret_key = "ff82b98ef8727e388ea8bff063"
csrf = CSRFProtect()
csrf.init_app(app)
if __name__ == "__main__":
app.run(host='127.0.0.1',debug=True)
Config.py
import json
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# from flask_wtf.csrf import CSRFProtect
from flask_login import LoginManager
from flask_cors import CORS, cross_origin
db = SQLAlchemy()
ma = Marshmallow()
f = open('configs.json')
config = json.load(f)
def create_app():
app = Flask(__name__, template_folder='templates')
app.config['SQLALCHEMY_DATABASE_URI'] = config['config']['database']
app.config['SECRET_KEY'] = config['config']['secret_key']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
api_v1_cors_config = {
"origins": ["*"]
}
CORS(app, resources={
r"/api/*": api_v1_cors_config
})
db.init_app(app)
ma.init_app(app)
login_manager = LoginManager()
login_manager.login_view = 'pages.login'
login_manager.init_app(app)
from models.user_management import User
#login_manager.user_loader
def load_user(user_id):
# since the user_id is just the primary key of our user table, use it in the query for the user
return User.query.get(int(user_id))
return app
api init.py folder with the name 'api' as the package
from flask import Blueprint
from flask_restful import Api
api_bp=Blueprint('api',__name__)
api = Api(api_bp)
# from .login import *
# from .api_project import *
from .project import *
# from .master_user import *
and lastly the project.py
from . import api
from flask import Flask, jsonify, request
from flask_restful import Resource, Api
from models.project_management import Project, ProjectStatus, Task
#api.add_resource(Project, '/v1/project')
class Project(Resource):
def get(self):
try:
print('test')
projects = Project.query.all()
return jsonify({
'message': 'Data get success',
'data': projects,
})
except Exception as e:
return jsonify({
'message': f'failed to get data {e}',
'data': []
})
enter code here
I can't check it but ...
You have the same name Project for model (Project.query.all()) and for class class Project(Resource) and this can make problem.
Because model Project is created (imported) before add_resource() so it uses this model but it has to use class Project
You may have to first define class with different name and later use add_resource() using new class
class MyProject(Resource):
# ... code ...
api.add_resource(MyProject, '/v1/project')

Python flask api routes 404 Not found error

As the title of the question says, all the routes which are not in the main file i.e. app.py are throwing Not Found 404 error. Below are the details of my small project:
Directory structure:
server
-> user
-> __init__.py
-> models.py
-> routes.py
-> app.py
-> __init__.py
app.py:
from flask import Flask
app = Flask(__name__)
from user import routes
#app.route('/') # THIS ROUTE WORKS
def index():
return '<h1>HOME</h1>'
if __name__ == '__main__':
app.run(debug = True)
routes.py:
from app import app
#app.route('/register', methods=['GET']) # THIS DOESN'T WORK - 404 NOT FOUND ERROR
def register_user():
return '<h1>Register a user!</h1>'
I cannot find out what is wrong here, I also tried the Blueprint method but I keep getting circular import error.
EDIT:
Flask Blueprint approach:
app.py:
from flask import Flask
from pymongo import MongoClient
app = Flask(__name__)
mongo_client = MongoClient(mongoUri)
db = mongo_client[DB_NAME]
from user.routes import bp
app.register_blueprint(bp)
#app.route('/')
def index():
return '<h1>HOME</h1>'
if __name__ == '__main__':
app.run(debug = True)
user/routes.py:
from flask import Blueprint, render_template_string
from user.models import User # if I comment this, it starts working...
bp = Blueprint('user', __name__)
#bp.route('/register', methods=['POST'])
def register_user():
user = User()
user.register()
return user
#bp.route('/register', methods=['GET'])
def check_user():
return render_template_string('<h1>User Registered</h1>')
user/models.py:
import uuid
from urllib import request
from flask import jsonify
from app import db # fishy...
class User(object):
def register(self):
user = {
'_id': uuid.uuid4().hex,
'email': request.form.get('email'),
'password': request.form.get('password'),
}
db.users.insert_one(user):
return jsonify(user), 200
I'm now getting this error as I mentioned earlier:
Traceback (most recent call last):
File "D:\project\server\app.py", line 10, in <module>
from user.routes import bp
File "D:\project\server\user\routes.py", line 2, in <module>
from user.models import User
File "D:\project\server\user\models.py", line 5, in <module>
from app import db
File "D:\project\server\app.py", line 10, in <module>
from user.routes import bp
ImportError: cannot import name 'bp' from partially initialized module 'user.routes' (most likely due to a circular import) (D:\project\server\user\routes.py)
You need to first define a Blueprint, and then use that for your routes/APIs. In route.py write this:
from flask import Blueprint, render_template_string
from user.models import User
bp = Blueprint('user', __name__)
#bp.route('/register', methods=['POST'])
def register_user():
user = User()
user.register()
return user
#bp.route('/register', methods=['GET'])
def check_user():
return render_template_string('<h1>User Registered</h1>')
Then you need to import and register your blueprint. In app.py have this:
from flask import Flask
app = Flask(__name__)
from user.routes import bp
app.register_blueprint(bp)
#app.route('/')
def index():
return '<h1>HOME</h1>'
if __name__ == '__main__':
app.run(debug = True)
Have another file in the same directory as app.py, you can call it extensions.py:
from pymongo import MongoClient
mongo_client = MongoClient(mongoUri)
db = mongo_client[DB_NAME]```
And finally models.py will look like this:
...
from extensions import db
...

Register blueprint in Python Flask unittest doesn't work

I can confirm that my unittest and api was already working but after moving my stuff to a Blueprint, my unittest kept on failing while the api is still working. I'm stumped, looking for ideas.
Here are the codes in question:
# project/app/__init__.py
from flask_sqlalchemy import SQLAlchemy
from flask import request, jsonify, abort, Flask
from instance.config import app_config
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
from app.api import api
app.register_blueprint(api, url_prefix='/api')
return app
Blueprint File
# project/app/api/__init__.py
from flask import Blueprint
api = Blueprint('api', __name__)
from app.api import campaigns
Test File
# project/test_campaigns.py
import unittest
import json
from app import create_app, db
from flask import Flask, Blueprint
from instance.config import app_config
class CampaignsTestCase(unittest.TestCase):
"""Campaigns Test Case"""
def setUp(self):
"""Define test varibles and initialize app."""
self.app = create_app(config_name="testing")
self.client = self.app.test_client
self.campaigns = {'name': 'Test Campaign'}
#binds the app to the current context
with self.app.app_context():
# create all tables
db.create_all()
def test_create_campaign(self):
"""Test API can create campaign (POST Request)"""
res = self.client().post('/api/campaigns/', data=self.campaigns)
self.assertEqual(res.status_code, 201)
self.assertIn('Test', str(res.data))
### REST OF TEST ####
API Route File. This is where I used the '/campaigns' route which will be prefixed by '/api'.
# project/app/api/campaigns.py
from app.api import api
from flask_sqlalchemy import SQLAlchemy
from flask import request, jsonify, abort, Flask
import os
#api.route('/campaigns/', methods=['POST'])
def create_campaign():
if request.method == 'POST':
name = request.form['name']
if name:
campaign = Campaign(name=name)
campaign.save()
response = jsonify({
'id': campaign.id,
'name': campaign.name,
'date_created': campaign.date_created
})
response.status_code = 201
return response
All of my test results into a 404
======================================================================
FAIL: test_create_campaign (__main__.CampaignsTestCase)
Test API can create campaign (POST Request)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_campaigns.py", line 25, in test_create_campaign
self.assertEqual(res.status_code, 201)
AssertionError: 404 != 201

Flask circular dependency

I am developing a Flask application. It is still relatively small. I had only one app.py file, but because I needed to do database migrations, I divided it into 3 using this guide:
https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
However, I now can't run my application as there is a circular dependency between app and models.
app.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import render_template, request, redirect, url_for
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.debug = True
db = SQLAlchemy(app)
from models import User
... routes ...
if __name__ == "__main__":
app.run()
models.py:
from app import db
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)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return self.username
manage.py:
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == "__main__":
manager.run()
They are all in the same directory. When I try to run python app.py to start the server, I receive an error which definitely shows a circular dependency (which is pretty obvious). Did I make any mistakes when following the guide or is the guide wrong? How can I refactor this to be correct?
Thanks a lot.
EDIT: Traceback
Traceback (most recent call last):
File "app.py", line 14, in <module>
from models import User
File "/../models.py", line 1, in <module>
from app import db
File "/../app.py", line 14, in <module>
from models import User
ImportError: cannot import name User
I propose the following structure:
# app/extensions.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...
# app/app.py
from app.extensions import db
def create_app(config_object=ProdConfig):
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
register_extensions(app)
...
def register_extensions(app):
db.init_app(app)
...
# manage.py
from yourapp.app import create_app
app = create_app()
app.debug = True
...
In this case, database, app, and your models are all in separate modules and there are no conflicting or circular imports.
I chased this for a few hours, landing here a few times, and it turned out I was importing my page modules (the ones holding the #app.route commands) before the line where the app was created. This is easy to do since import commands tend to be placed at the very beginning, but it doesn't work in this case.
So this:
# app/__init__.py
print("starting __init__.py")
from flask import Flask
from flask import render_template
import matplotlib.pyplot as plt
import numpy as np
import mpld3
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config')
from . import index
from . import simple
app.run(threaded=False)
print("finished __init__.py")
Instead of having all imports on top.
Placing this here because this has to be a common error for casual flask users to encounter and they are likely to land here. I have hit it as least twice in the last couple of years.

Categories

Resources