Flask报如下错误:SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.

在同一个项目中由于flask_sqlalchemy版本不同,有时会报如下错误

错误信息如下:

flask_sqlalchemy\__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.')

错误信息提示的很明确,修改 SQLALCHEMY_TRACK_MODIFICATIONS 为True以移除这个警告。

 

去flask/lib/python2.7/site-packages/flask_sqlalchemy的init.py里面修改吧。

 

 


在init.py里面有init_app方法,修改下面的一行:

track_modifications = app.config.setdefault[SQLALCHEMY_TRACK_MODIFICATIONS',True]

然后保存,运行。

 

注意

在后面程序中仍然出现错误

>>> from app import db,models
>>> u = models.User(nickname=johnjohn@email.com')
>>> db.session.add(u)
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
  File /Users/simufengyun/microblog/flask/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py162,1)">in do
    return getattr(self.registry(),name)(*args,**kwargs)
  File /Users/simufengyun/microblog/flask/lib/python2.7/site-packages/sqlalchemy/util/_collections.py1012,1)">in __call__
    return self.registry.setdefault(key,self.createfunc())
  File /Users/simufengyun/microblog/flask/lib/python2.7/site-packages/sqlalchemy/orm/session.py3214,1)">return self.class_(**local_kw)
  File /Users/simufengyun/microblog/flask/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py137,1)"> __init__
    #track_modifications = app.config[]
KeyError: (

 

 

请参考如下文章进行修改:https://github.com/pallets/flask-sqlalchemy/issues/609 

关于KeyError的错误:。

# __init__.py
class SignallingSession(SessionBase):

    def __init__(self,db,autocommit=False,autoflush=True,1)">options):
        #: The application that  session belongs to.
        self.app = app = db.get_app()
        track_modifications = app.config[]
        bind = options.pop(bind,None) or db.engine
        binds = options.pop(bindsif track_modifications is None or track_modifications:
            _SessionSignalEvents.register(self)

        SessionBase.__init__(
            self,autocommit=autocommit,autoflush=autoflush,bind=bind,binds=binds,1)">options
        )
关键字“SQLALCHEMY_TRACK_MODIFICATIONS”不在app.config中,app.config在使用前未初始化。所以我建议稍微改变如下:

刚刚在“self.session = self.create_scoped_session(session_options)”之前初始化了“self.app = app”。
# __init__.py
class SQLAlchemy(object):
    """This class is used to control the SQLAlchemy integration to one
    or more Flask applications.  Depending on how you initialize the
    object it is usable right away or will attach as needed to a
    Flask application.
    ... ... ...
    .. versionchanged:: 3.0
       Utilise the same query  across `session`,`Model.query` and `Query`.
    """

    #: Default query  used by :attr:`Model.query` and other queries.
    #: Customize  by passing ``query_class`` to :func:`SQLAlchemy`.
    #: Defaults to ::`BaseQuery`.
    Query = None

    def __init__(self,app=None,use_native_unicode=True,session_options=None,metadata=None,query_class=BaseQuery,model_class=Model):
        self.app = app
        self.use_native_unicode = use_native_unicode
        self.Query = query_class
        self.session = self.create_scoped_session(session_options)
        self.Model = self.make_declarative_base(model_class,metadata)
        self._engine_lock = Lock()
        # self.app = app

        _include_sqlalchemy(self,query_class)

        if app  not None:
            self.init_app(app)
添加代码:
        if self.app  not None:
             self.app
代码之前:

        if current_app:
             current_app._get_current_object()
如下:

# __init__.py

    def get_app(self,reference_app=None):
        Helper method that implements the logic to look up an
        application."""

        if reference_app  reference_app

        if self.app is not None:
            return self.app

         current_app._get_current_object()

        #  not None:
        #    self.app

        raise RuntimeError(
            No application found. Either work inside a view function or push'
             an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
        )
这样,“self.app = app = db.get_app()”将返回实例参数“app”通过“SQLAlchemy(app)”传输,而不是引发错误。

因为,代码中的“self.app”

         self.app
不会是None,也不会出错。

现在我们可以在使用“db = SQLAlchemy(app)”作为下面的代码之前初始化“app.config”:

#coding:utf8
import pymysql
 flask_sqlalchemy import SQLAlchemy
 flask import Flask

app = Flask(__name__)

app.config[SQLALCHEMY_DATABASE_URI"] = mysql+pymysql://root:whm@47.x.x.x:3306/artcs_pro"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

db = SQLAlchemy(app)

  注意以上所有修改操作都要重新启动 flask/bin/python

原文地址:https://www.cnblogs.com/zmdComeOn

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Jinja2:是Python的Web项目中被广泛应用的模板引擎,是由Python实现的模板语言,Jinja2 的作者也是 Flask 的作者。他的设计思想来源于Django的模板引擎,并扩展了其语法和一系列强大的功能,其是Flask内置的模板语言。
Fullcalendar日历使用,包括视图选择、事件插入、编辑事件、事件状态更改、事件添加和删除、事件拖动调整,自定义头部,加入el-popover显示图片、图片预览、添加附件链接等,支持手机显示。
监听QQ消息并不需要我们写代码,因为市面上已经有很多开源QQ机器人框架,在这里我们使用go-cqhttp官方文档:go-cqhttp如果您感兴趣的话,可以阅读一下官方文档,如果不想看,直接看我的文章即可。
【Flask框架】—— 视图和URL总结
python+web+flask轻量级框架的实战小项目。登录功能,后续功能可自行丰富。
有了这个就可以配置可信IP,关键是不需要企业认证,个人信息就可以做。
本专栏是对Flask官方文档中个人博客搭建进行的归纳总结,与官方文档结合事半功倍。 本人经验,学习一门语言或框架时,请首先阅读官方文档。学习完毕后,再看其他相关文章(如本系列文章),才是正确的学习道路。
本专栏是对Flask官方文档中个人博客搭建进行的归纳总结,与官方文档结合事半功倍。基础薄弱的同学请戳Flask官方文档教程 本人经验,学习一门语言或框架时,请首先阅读官方文档。学习完毕后,再看其他相关文章(如本系列文章),才是正确的学习道路。 如果python都完全不熟悉,一定不要着急学习框架,请首先学习python官方文档,一步一个脚印。要不然从入门到放弃是大概率事件。 Python 官方文档教程
快到年末了 相信大家都在忙着处理年末数据 刚好有一个是对超市的商品库存进行分析的学员案例 真的非常简单~
一个简易的问答系统就这样完成了,当然,这个项目还可以进一步完善,比如 将数据存入Elasticsearch,通过它先进行初步的检索,然后再通过这个系统,当然我们也可以用其他的架构实现。如果你对这系统还有其他的疑问,也可以再下面进行留言!!!
#模版继承和页面之间的调用@app.route(&quot;/bl&quot;)def bl(): return render_template(&quot;file_2.html&quot;)主ht
#form表达提交@app.route(&quot;/data&quot;,methods=[&#39;GET&#39;,&#39;POST&#39;]) #methods 让当前路由支持GET 和
#form表达提交@app.route(&quot;/data&quot;,methods=[&#39;GET&#39;,&#39;POST&#39;]) #methods 让当前路由支持GET 和
#session 使用app.secret_key = &quot;dsada12212132dsad1232113&quot;app.config[&#39;PERMANENT_SESSION_LI
#文件上传@app.route(&quot;/file&quot;,methods=[&#39;GET&#39;,&#39;POST&#39;])def file(): if request.meth
#跳转操作:redirect@app.route(&quot;/red&quot;)def red(): return redirect(&quot;/login&quot;)
#session 使用app.secret_key = &quot;dsada12212132dsad1232113&quot;app.config[&#39;PERMANENT_SESSION_LI
@app.route(&quot;/req&quot;,methods=[&#39;GET&#39;,&#39;POST&#39;])def req(): print(request.headers)
#模版继承和页面之间的调用@app.route(&quot;/bl&quot;)def bl(): return render_template(&quot;file_2.html&quot;)主ht
#文件操作:send_file,支持图片 视频 mp3 文本等@app.route(&quot;/img&quot;)def img(): return send_file(&quot;1.jpg&q