I have a function called generate_csrf_token which is located in package commons.formsecurity containing the following code.
import random
import string
from flask import session
def generate_csrf_token():
if '_csrf_token' not in session:
state = ''.join(random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
session['_csrf_token'] = state
return session['_csrf_token']
I am calling this in my create_app function.
from flask import Flask
from routes_manager import configure_blueprints
from error_handling import configure_error_handling
from flask import session
from flask.ext.session import Session
from commons.formsecurity import generate_csrf_token
def create_app():
"""Create the Flask App"""
app = Flask(__name__)
app.secret_key = 'lalalalalala'
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
configure_blueprints(app)
configure_error_handling(app)
return app
create_app is called from main.py
from app import create_app
app = create_app()
"""Run the clients"""
if __name__ == '__main__':
app.run(debug=True)
When I run my Flask application. I get the following error.
ERROR 2017-05-25 12:12:50,720 wsgi.py:263]
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "C:\Code\App-Engine\cfc-melbourne-website\main.py", line 3, in <module>
app = create_app()
File "C:\Code\App-Engine\cfc-melbourne-website\app\__init__.py", line 12, in create_app
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
File "C:\Code\App-Engine\cfc-melbourne-website\app\commons\formsecurity.py", line 7, in generate_csrf_token
if '_csrf_token' not in session:
File "lib\werkzeug\local.py", line 379, in <lambda>
__contains__ = lambda x, i: i in x._get_current_object()
File "lib\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "lib\flask\globals.py", line 37, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
Where is the best place to call the following
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
If you don't call the generate_csrf_token() function, and instead store the reference to the function, you can call it in your Jinja templates (which will be in the context where a request is available).
So replace
app.jinja_env.globals['csrf_token'] = generate_csrf_token()
With
app.jinja_env.globals['csrf_token'] = generate_csrf_token
And in your templates, use:
<input name=_csrf_token type=hidden value="{{ csrf_token() }}">
Related
I have a simple flash website created and deployed in a server with Nginx as frontend and gunicorn as backend to run the python code. With this setup everything is working fine. However, if i run the server using supervisor module, I'm getting below error. I have ensured all the environment variables are accessible, they are placed in .bashrc under home directory.
Not sure what am missing. My python code is deployed in server inside a pipenv virtual environment. supervisor was started within the virtualenv only. Not sure if it has any relevance.
error log with supervisor
[2020-11-10 05:45:29,604] ERROR in app: Exception on /home [GET]
Traceback (most recent call last): File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/util/_collections.py",
line 1020, in call
return self.registry[key] KeyError: 139749229659968
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 2447, in wsgi_app
response = self.full_dispatch_request() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1952, in full_dispatch_request
rv = self.handle_user_exception(e) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/_compat.py",
line 39, in reraise
raise value File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1950, in full_dispatch_request
rv = self.dispatch_request() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask/app.py",
line 1936, in dispatch_request
return self.view_functionsrule.endpoint File "/home/anandraj/FlaskProject/Proj2/main/routes.py", line 12, in home
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page,
per_page=7) File
"/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 514, in get
return type.query_class(mapper, session=self.sa.session()) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py",
line 78, in call
return self.registry() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/util/collections.py",
line 1022, in call
return self.registry.setdefault(key, self.createfunc()) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/sqlalchemy/orm/session.py",
line 3300, in call
return self.class(**local_kw) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 138, in init
bind = options.pop('bind', None) or db.engine File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 943, in engine
return self.get_engine() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 962, in get_engine
return connector.get_engine() File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 555, in get_engine
options = self.get_options(sa_url, echo) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 570, in get_options
self._sa.apply_driver_hacks(self._app, sa_url, options) File "/home/anandraj/.local/share/virtualenvs/FlaskProject-tLcktdEC/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 883, in apply_driver_hacks
if sa_url.drivername.startswith('mysql'): AttributeError: 'NoneType' object has no attribute 'drivername'
Supervisor config
cat /etc/supervisor/conf.d/supervisord.conf
[program:Proj2]
directory=/home/<user>/FlaskProject
command=/home/<user>/.local/share/virtualenvs/FlaskProject->tLcktdEC/bin/gunicorn -w 3 run:app
user=<user>
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stderr_logfile=/var/log/flaskblog/Proj2Flask.err.log
stdout_logfile=/var/log/flaskblog/Proj2Flask.out.log
Error while querying DB
~/FlaskProject/Proj2/main$ cat routes.py
from flask import render_template, request, Blueprint
from Proj2.models import Post
main = Blueprint('main', __name__)
#main.route("/")
#main.route("/home")
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=7)
return render_template('home.html', posts=posts)
#main.route("/about")
def about():
return render_template('about.html', title='Anandraj')
How my app is initialized?
~/FlaskProject/Proj2$ cat __init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from Proj2.config import Config
db = SQLAlchemy()
bcrypt = Bcrypt()
login_mgr = LoginManager()
login_mgr.login_view = 'users.login'
login_mgr.login_message_category = 'info'
mail = Mail()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_mgr.init_app(app)
mail.init_app(app)
from Proj2.users.routes import users
from Proj2.posts.routes import posts
from Proj2.main.routes import main
from Proj2.errors.handler import errors
app.register_blueprint(users)
app.register_blueprint(posts)
app.register_blueprint(main)
app.register_blueprint(errors)
return app(FlaskProject)
Can you post your supervisor config file? My guess here is that it's related to your PATH definition...
EDIT (12/Nov): After seeing you're supervisor config file I noticed that you haven't set the environment path.
A list of key/value pairs in the form KEY="val",KEY2="val2" that will be placed in the supervisord process’ environment (and as a result in all of its child process’ environments)
from: https://docs.red-dove.com/supervisor/configuration.html
Can you try adding this to your configuration file? This will define your PATH as "/usr/bin/" for the environment that runs your gunicorn. If that doesn't work, please try use the path from where your virtualenv is running.
environment=PATH="/usr/bin"
I'm programming a Website with Authentification while using the Flask Framework. I've tried every solution that i found on the internet but nothing worked for me.
My first idea was, that the Project Structure was corrupt. e.g. missing imports from other files. But thats not the problem i think.
My models.py File:
from flask_login import UserMixin, LoginManager
from flaskapp import db, login_manager
#login_manager.user_loader
def get_user(user):
try:
return get_id(user)
except:
return None
class User(db.Model,UserMixin):
id =db.Column(db.Integer, primary_key=True)
username =db.Column(db.String(20),unique=True, nullable=False)
email =db.Column(db.String(120), unique=True, nullable=False)
password =db.Column(db.String(60), nullable=False)
powerlevel =db.Column(db.Integer, nullable=False)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return int(self.id)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.powerlevel}')"
My init.py File:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = 'xxx'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager = login_message_category = 'info'
from flaskapp import routes
When running the WebApp using:
export FLASK_APP=run.py DEBUG=TRUE
flask run
Following Error Message Occurs:
Traceback (most recent call last):
File "/home/osboxes/.local/bin/flask", line 11, in <module>
sys.exit(main())
File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 966, in main
cli.main(prog_name="python -m flask" if as_module else None)
File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/osboxes/.local/lib/python3.6/site-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/home/osboxes/.local/lib/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 848, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 305, in __init__
self._load_unlocked()
File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/home/osboxes/.local/lib/python3.6/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/home/osboxes/Desktop/HMI/run.py", line 1, in <module>
from flaskapp import app
File "/home/osboxes/Desktop/HMI/flaskapp/__init__.py", line 21, in <module>
from flaskapp import routes
File "/home/osboxes/Desktop/HMI/flaskapp/routes.py", line 6, in <module>
from flaskapp.models import User
File "/home/osboxes/Desktop/HMI/flaskapp/models.py", line 7, in <module>
#login_manager.user_loader
AttributeError: 'str' object has no attribute 'user_loader'
Right now i don't know what else could be the problem.
If i forgot to supply some code for solving the error, let me know.
Thank you for your Help!
First, your User.get_id should be returning unicode not an int. The documentation mentions this, along with an example:
This method must return a unicode that uniquely identifies this user,
and can be used to load the user from the user_loader callback. Note
that this must be a unicode - if the ID is natively an int or some
other type, you will need to convert it to unicode. (Your User
Class)
So that needs to be changed to:
def get_id(self):
return unicode(self.id)
Next up, your user_loader. From the docs:
This sets the callback for reloading a user from the session. The
function you set should take a user ID (a unicode) and return a user
object, or None if the user does not exist.
Which would mean adjusting your user_loader to be something like:
#login_manager.user_loader
def get_user(user_id):
try:
return User.query.get(int(user_id))
except:
return None
Also, you have an error here, which is likely the direct cause of the error:
login_manager = login_message_category = 'info'
So your taking your login_manager and replacing it with a string with the contents 'info'. So later when your app tries to access login_manager.user_loader it's failing, because a string 'info' doesn't have a user_loader method.
Changing it to the below should fix the error. Though the other issues addressed above also need to be implemented.
login_manager.login_message_category = 'info'
You have used the login_manager = LoginManager(app) you are creating an object along with the configuration. Insider of that create an object first and configure the object in 2 steps.
login_manager = LoginManager()
login_manager.init_app(app)
for more reference please check the link here[https://flask-login.readthedocs.io/en/latest/]
you may need to update in your init.py file.
I'm trying to build a blog as a portfolio sample using python3 and flask and flask_jwt_extended.
I can create a single file like this and it will run:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
#app.route(....)
#jwt required
But when I try to use Blueprint, it will not register the JWTManager
Here is my user.py file:
from flask_jwt_extended import (create_access_token, get_jwt_identity, JWTManager, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'this-is-super-secret'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt = JWTManager(app)
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt required
here is my app.py:
from user import *
app = Flask(__name__)
app.register_blueprint(user_blueprint)
Now when I try to run app.py, this it returns a 500 (Internal Error) and will log this to the log file:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 127, in _get_jwt_manager
return current_app.extensions['flask-jwt-extended']
KeyError: 'flask-jwt-extended'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ali/Desktop/cetia_api/user.py", line 63, in login
return create_token(user_inputs)
File "/home/ali/Desktop/cetia_api/user_functions.py", line 103, in create_token
access_token = create_access_token(identity=data, expires_delta=expires)
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 156, in create_access_token
jwt_manager = _get_jwt_manager()
File "/usr/local/lib/python3.6/dist-packages/flask_jwt_extended/utils.py", line 129, in _get_jwt_manager
raise RuntimeError("You must initialize a JWTManager with this flask "
RuntimeError: You must initialize a JWTManager with this flask application before using this method
Could someone please tell me what to do? I tried EVERYTHING for the last 3 days. its been 20 hours of debugging and it's still not fixed
You need to use the same app in every location. Currently you are creating an app in your users.py file, and a different app in you app.py file.
Generally you will want to use the flask application factory pattern to do this (https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/). An example might look something like this:
extensions.py
from flask_jwt_extended import JWTManager
jwt = JWTManager()
users.py
from flask_jwt_extended import (create_access_token, get_jwt_identity, jwt_required, get_raw_jwt)
from flask import Flask, request, Blueprint
user_blueprint = Blueprint('user_blueprint', __name__)
#user_blueprint.route(....)
#jwt_required
app.py
from extensions import jwt
from users import users_blueprint
def create_app():
app = Flask(__name__)
app.secret_key = 'ChangeMe!'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
jwt.init_app(app)
app.register_blueprint(user_blueprint)
return app
main.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
I'm debugging an error, when I try to query from my database to populate the fields of my FlaskForm, I get the following error:
Traceback (most recent call last):
File "manage.py", line 16, in <module>
app = create_app(os.getenv('DVR_CONFIG') or 'default')
File "C:\Users\---\myapp\\app\__init__.py", line 42, in create_app
from .main import main as main_blueprint
File "C:\Users\---\myapp\\app\main\__init__.py", line 5, in <module>
from . import views, errors
File "C:\Users\---\myapp\\app\main\views.py", line 5, in <module>
from .forms import CharacterSelect
File "C:\Users\---\myapp\\app\main\forms.py", line 15, in <module>
class CharacterSelect(FlaskForm):
File "C:\Users\---\myapp\\app\main\forms.py", line 17, in CharacterSelect
user = User.query.filter_by(unique_name=session.get('unique_name')).first()
File "C:\Python27\lib\site-packages\flask_sqlalchemy\__init__.py", line 500, in __get__
return type.query_class(mapper, session=self.sa.session())
File "C:\Python27\lib\site-packages\sqlalchemy\orm\scoping.py", line 78, in __call__
return self.registry()
File "C:\Python27\lib\site-packages\sqlalchemy\util\_collections.py", line 990, in __call__
return self.registry.setdefault(key, self.createfunc())
File "C:\Python27\lib\site-packages\flask_sqlalchemy\__init__.py", line 771, in create_session
return SignallingSession(self, **options)
File "C:\Python27\lib\site-packages\flask_sqlalchemy\__init__.py", line 153, in __init__
self.app = app = db.get_app()
File "C:\Python27\lib\site-packages\flask_sqlalchemy\__init__.py", line 922, in get_app
raise RuntimeError('application not registered on db '
RuntimeError: application not registered on db instance and no application bound to current context
Here is the offending code:
from ..models import User
class CharacterSelect(FlaskForm):
user = User.query.filter_by(unique_name=session.get('unique_name')).first()
charId0 = user.characterId_0
charId1 = user.characterId_1
charId2 = user.characterId_2
user_list = [charId0, 'Char0', charId1, 'Char1', charId2, 'Char2']
new_user_list = [x for x in user_list if x is not None]
selectedUser = SelectField(u'Character Select', choices=user_list)
From researching this error, it appears Flask doesn't know which app my DB is attached to. Also most of the stackoverflow answers I have seen recommend using:
with app.app_context():
:
:
db.create_all()
However, from working through Miguels Flask Book and Flasky blog, he doesn't seem to need to use "with app.app_context()" and only uses "db.create_all()" in his unit test code. Miguel inits the DB like so:
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
:
:
db.init_app(app)
Any help in debugging and understanding this error is much appreciated!
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
db.init_app(app)
return app
Many things are nor clear from your code snippet. What is obvious however is that you have to have your db.init_app(app) inside your create_app() function. Then you would return app object from the function. Most preferably in different module i.e. manage.py (this really depends on your application structure)
from somewhere import create_app
app = create_app(config_name)
if __name__ == "__main__":
app.run()
Now variable app is your application instance with db registered.
Someone has pointed me to the FlaskForm Docs, where the is a pretty sparse example.
Esentially I need to create the tuple list in my views.py and pass it into my Form Object, see below for details:
views.py:
user = g.user
charId0 = user.characterId_0
charId1 = user.characterId_1
charId2 = user.characterId_2
user_list = [(charId0, 'Char0'), (charId1, 'Char1'), (charId2, 'Char2')]
form = CharacterSelect(request.form)
form.selectedUser.choices = user_list
forms.py:
class CharacterSelect(FlaskForm):
selectedUser = SelectField(u'Character Select', choices=[])
I'm following this book called: "Flask web development".
When I'm creating the login system he creates then I can an exception at my registration of the blueprint I have made.
Log:
C:\Python27\python.exe "C:/Users/Bo/Google Drev/Privat/HobbyProjekter/Event/manage.py"
Traceback (most recent call last):
File "C:/Users/Bo/Google Drev/Privat/HobbyProjekter/Event/manage.py", line 7, in <module>
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
File "C:\Users\Bo\Google Drev\Privat\HobbyProjekter\Event\app\__init__.py", line 42, in create_app
app.register_blueprint(auth_blueprint, url_prefix='/auth')
File "C:\Python27\lib\site-packages\flask\app.py", line 62, in wrapper_func
return f(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\flask\app.py", line 889, in register_blueprint
blueprint.register(self, options, first_registration)
File "C:\Python27\lib\site-packages\flask\blueprints.py", line 153, in register
deferred(state)
File "C:\Python27\lib\site-packages\flask\blueprints.py", line 172, in <lambda>
s.add_url_rule(rule, endpoint, view_func, **options))
File "C:\Python27\lib\site-packages\flask\blueprints.py", line 76, in add_url_rule
view_func, defaults=defaults, **options)
File "C:\Python27\lib\site-packages\flask\app.py", line 62, in wrapper_func
return f(self, *args, **kwargs)
File "C:\Python27\lib\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: auth.login
The code for where I register my blueprint looks like this:
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
And that code imports from my auth__init__.py :
from flask import Blueprint
auth = Blueprint('auth', __name__)
from . import views
from flask import render_template
from . import auth
#auth.route('/login')
def login():
return render_template('auth/login.html')
At last my view I'm trying to register (just a snippet):
#auth.route('/login', methods=['GET', 'POST'])
def login():
Hope you can help
You have 2 endpoints called '/login'. Change one of their names. Also the functions can't have the same names either.