在应用程序上下文之外工作-Flask [英] working outside of application context - Flask
问题描述
def get_db(self,dbfile):
if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db)
try:
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
except sqlite3.OperationalError as e:
raise e
return g.sqlite_db
您好,这段代码位于DB类内部,我得到的错误是
Hi this code is located inside DB class, The error I get is
RuntimeError:在应用程序上下文之外工作
RuntimeError: working outside of application context
此行发生错误
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
我认为问题出在g上,它是像from flask import g
I think the problem is with g, it is imported like that from flask import g
如何解决此错误? 谢谢.
How this error can be fixed? Thanks.
推荐答案
来自flask/globals.py
中的Flask源代码:
From the Flask source code in flask/globals.py
:
_app_ctx_err_msg = '''\
Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in a way. To solve
this set up an application context with app.app_context(). See the
documentation for more information.\
'''
根据文档,您可以看到您需要将flask.current_app
指向您的应用程序,而当前并不需要.
Following the documentation, you can see that you need to make flask.current_app
point to your application and it currently doesn't.
您可能在Flask初始化之前调用了DB函数.我的猜测是您的app
对象尚未使用Flask
构造函数创建.
You're probably calling your DB function before Flask has initialized. My guess is that your app
object has not been created yet with the Flask
constructor.
这篇关于在应用程序上下文之外工作-Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!