Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

working outside of application context - Flask

Tags:

python

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

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.

like image 663
Koten Avatar asked Dec 06 '15 21:12

Koten


4 Answers

Maybe you need to call your function inside an application context:

with app.app_context():
  # call your method here
like image 103
VadimK Avatar answered Oct 16 '22 18:10

VadimK


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.

like image 39
Juan Pablo Santos Avatar answered Oct 16 '22 17:10

Juan Pablo Santos


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

like image 16
Сергей Осечкин Avatar answered Oct 16 '22 18:10

Сергей Осечкин


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()

like image 2
user2682863 Avatar answered Oct 16 '22 19:10

user2682863