14

I am trying to follow the instructions from the following tutorial:

Tutorial

I downloaded the code from the following repo:

Repo

However when I run it locally and try to add something to the database, I get the following error:

builtins.KeyError
KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'

When I tried to read the traceback, I realised that even if I add a variable SQLALCHEMY_TRACK_MODIFICATIONS to the config file, some python library file is unable to recognise it exists.

Looks like there is another answer to a similar question, but that was more like a quick fix, not why this is happening.

I would like to know why this is happening and how to fix it.Preferably without changing the whole structure.

Thanks a lot in advance.

4 Answers 4

35

Having two app = Flask(__name__) in the code can cause this problem.

That was my case, I removed one and kept the one in the app's folder's __init__.py, and it worked

Sign up to request clarification or add additional context in comments.

1 Comment

Another reason for this error is forgetting the db.init_app(app)
8

I solved this problem by this way.
Remove the current one, and replace the old version.

pip3 uninstall flask-sqlalchemy
pip3 install flask-sqlalchemy==2.1.0

2 Comments

Wow. That worked like a charm. Never expected that changing the version would do such a wonder. Thanks a lot
I'm not sure I understand this solution. We are now on version 2.4.1 and this issue exists in scenarios.
3

@Javier's answer gave me a direction to problem as mentioned reason of error is having multiple flask apps.

Apart from creating app in __init__.py one more solution which worked was to use newly created app's context to run the query and boom!!! error was gone.

Below is code snippet for using newly created app's context:-

app = Flask(__name__)
app.config.from_pyfile('./config.py')
init_app(app)

def create():
    with app.app_context():
       #Below Tags is model class 
       tag = Tags(**data)
       db.session.add(tag)
       db.session.commit()
       return from_sql(tag)

1 Comment

Where is config.py ? please add it there
2

I had same problem .. i am using connexion

The solution which worked for me was removing one instance of connexion object in server.py. You need to init connex_app in the config file then load the object in server like this:

in my config.py

connex_app = connexion.App(__name__, specification_dir=basedir)

and in my server.py

import config

connex_app = config.connex_app

This way using the object which is already instantiated worked for me !!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.