Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask, SQLAlchemy : KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'

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.

like image 955
Mahathi Vempati Avatar asked Jul 24 '17 06:07

Mahathi Vempati


4 Answers

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

like image 190
Javier PR Avatar answered Oct 19 '22 00:10

Javier PR


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 !!!

like image 20
Lavanya Rani Avatar answered Oct 19 '22 01:10

Lavanya Rani


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
like image 8
SeungWook Kim Avatar answered Oct 19 '22 01:10

SeungWook Kim


@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)
like image 3
vinit payal Avatar answered Oct 19 '22 00:10

vinit payal