Work out of application context - bulb

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 inside the DB class. The error I get is

RuntimeError: working out of application context

an 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 as from flask import g

How can this error be fixed? Thanks.

+9
source share
4 answers

From Flask source code to 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 what you need to do flask.current_app for your application, and currently it is not.

You probably call your DB function before initializing Flask. I assume that your app object has not yet been created using the Flask constructor.

+9
source

Maybe you need to call your function in the application context:

 with app.app_context(): # call your method here 
+10
source

When creating the application, use:

 app.app_context().push() 

for example like this:

 from yourapp import create_app app = create_app() app.app_context().push() 

for more information

0
source

ERROR. This usually means that you tried to use the functionality that is needed to interact with the current application object. Solving this created an application context with app.app_context (). See the documentation for more information.

-4
source

Source: https://habr.com/ru/post/1237526/


All Articles