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
Hi this code is located inside DB class, The error I get is
RuntimeError: working outside of application context
the error occurs on this line
g.sqlite_db = self.connect_db('{}/{}'.format(app.root_path, dbfile))
I think the problem is with g, it is imported like that from flask import g
How this error can be fixed? Thanks.
Maybe you need to call your function inside an application context:
with app.app_context():
# call your method here
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.\
'''
Following the documentation, you can see that you need to make flask.current_app
point to your application and it currently doesn't.
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.
When creating your app, use:
app.app_context().push()
for example like this:
from yourapp import create_app
app = create_app()
app.app_context().push()
for further information
To expand on @VadimK's answer. If you want to prevent your code from executing outside of an app_context
you can use flask.has_app_context() to see if the code is currently inside an app context:
See also: flask.has_request_context()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With