Koten Koten - 2 months ago 13x
Python Question

working outside of application context - Flask

def get_db(self,dbfile):
if hasattr(g, 'sqlite_db'): self.close_db(g.sqlite_db)
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?


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.