Flask, SQLAlchemy : KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'

橙三吉。 提交于 2020-04-02 16:42:04

问题


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.


回答1:


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




回答2:


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



回答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)


来源:https://stackoverflow.com/questions/45274152/flask-sqlalchemy-keyerror-sqlalchemy-track-modifications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!