Skip to content
Advertisement

What triggers the KeyError: ‘SQLALCHEMY_TRACK_MODIFICATIONS’?

I already looked at other threads concerning this error, which all indicate that this error is due to multiple instances of “app = Flask(name)”. But since I only have one, I hope someone here can help me figure this one out.

I try to keep the code minimal, but enough to reproduce the error

routes.py:

from flask import Flask, render_template, request, session, redirect, url_for
from models import db, User, Events, Bookings
from forms import SignupForm
from datetime import datetime, time

app = Flask(__name__)


app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://link'


app.secret_key = "secret"


@app.route("/register", methods=['GET', 'POST'])
def signup():
    form = SignupForm()
    
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('register.html', form=form)
        else:
            username = form.username.data
            email = form.email.data
            role = 'user'
            confirmed = True
            created_on = datetime.now()
            password = form.password.data
            newuser = User(username, email, role, confirmed, created_on, password)
            db.session.add(newuser)
            db.session.commit()
    elif request.method == 'GET':
        return render_template('register.html', form=form)
        
if __name__ == '__main__':
    app.run(debug=True)

models.py:

from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash


db = SQLAlchemy()


class User(db.Model):
    __tablename__ = 'users'
    uid = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(100), unique=True)
    email = db.Column(db.String(100), unique=True)
    role = db.Column(db.String(20), nullable=False)
    confirmed = db.Column(db.Boolean, nullable=False, default=False)
    created_on = db.Column(db.DateTime, nullable=False)
    pwdhash = db.Column(db.String(66), nullable=False)

    def __init__(self, username, email, role, confirmed, created_on, password):
        self.username = username
        self.email = email
        self.role = role
        self.confirmed = confirmed
        self.created_on = created_on
        self.set_password(password)

    def set_password(self, password):
        self.pwdhash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.pwdhash, password)

create statements for the Postgres Database:

CREATE TABLE users (
    uid serial PRIMARY KEY UNIQUE NOT NULL,
    username VARCHAR ( 50 ) UNIQUE NOT NULL,
    email VARCHAR ( 255 ) UNIQUE NOT NULL,
    role VARCHAR ( 50 ) NOT NULL,
    confirmed BOOLEAN NOT NULL,
    created_on TIMESTAMPTZ NOT NULL,
    pwdhash VARCHAR ( 66 ) NOT NULL
);

EDIT: THIS IS THE ERROR LOG:

File "C:UsersLuMicrossfittest.py", line 30, in signup
            role = 'user'
            confirmed = True
            created_on = datetime.now()
            password = form.password.data
            newuser = User(username, email, role, confirmed, created_on, password)
            db.session.add(newuser)Open an interactive python shell in this frame
            db.session.commit()
    elif request.method == 'GET':
        return render_template('register.html', form=form)
 
if __name__ == '__main__':
File "<string>", line 2, in add
 
File "C:UsersLuMicrossfitvenvLibsite-packagessqlalchemyormscoping.py", line 23, in _proxied
return self.registry()
File "C:UsersLuMicrossfitvenvLibsite-packagessqlalchemyutil_collections.py", line 1010, in __call__
return self.registry.setdefault(key, self.createfunc())
File "C:UsersLuMicrossfitvenvLibsite-packagessqlalchemyormsession.py", line 4101, in __call__
return self.class_(**local_kw)
File "C:UsersLuMicrossfitvenvLibsite-packagesflask_sqlalchemy__init__.py", line 175, in __init__
track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS']
KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'

Advertisement

Answer

You need to restructure your code.

remove the flask_sqlalchemy import from models.py and add it in routes.py

bring this line just before app.route(/register)….

from models import db, User, Events, Bookings

remove db = SQLAlchemy() this from models.py and add this import statement

from routes import db 

and finally include this line

db = SQLAlchemy(app)

below app.secret_key = "secret"

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement