I am receiving the ‘RuntimeError: Working outside of application context.’ error in my flask application and am struggling to understand why. I have tried to push the app context, however that didn’t seem to work for me and I may just be slightly confused as to how to access the ‘current_app’ so I can write to my logger from other classes and blueprints. My code is as follows:
run.py:
JavaScript
x
12
12
1
#! /usr/bin/python3.6
2
from caffeine import create_app
3
import os
4
5
app = create_app()
6
7
SECRET_KEY = b'x84xde=xc4x1c%rxf9Btxd3xcexc4oxaexf7'
8
app.secret_key = SECRET_KEY
9
10
if __name__ == '__main__':
11
app.run(debug=False, host="0.0.0.0", port=8000)
12
init.py:
JavaScript
1
52
52
1
import os
2
import logging
3
from flask import session
4
from datetime import timedelta
5
from pathlib import Path
6
from flask import Flask
7
from flask_sqlalchemy import SQLAlchemy
8
from flask_login import LoginManager
9
from caffeine.config import Config
10
11
# Create db instance
12
db = SQLAlchemy()
13
14
# create login manager instance
15
login_manager = LoginManager()
16
17
def create_app():
18
"""
19
Iinstantiates and initialize the Flask application
20
"""
21
app = Flask(__name__)
22
app.config.from_object(Config)
23
db.init_app(app)
24
login_manager.init_app(app)
25
login_manager.login_view = 'bp_auth.login'
26
login_manager.refresh_view = 'bp_auth.login'
27
login_manager.login_message_category = 'info'
28
29
# import Blueprint objects for routes
30
from caffeine.routes.bp_aiq_bundle import main
31
from caffeine.routes.bp_auth import auth
32
from caffeine.routes.bp_bundle import bundle
33
from caffeine.routes.bp_aiq import aiq
34
from caffeine.errors.handlers import errors
35
app.register_blueprint(main)
36
app.register_blueprint(auth)
37
app.register_blueprint(bundle)
38
app.register_blueprint(aiq)
39
app.register_blueprint(errors)
40
41
@app.before_request
42
def before_request():
43
session.permanent = True
44
app.permanent_session_lifetime = timedelta(minutes=1440)
45
46
# instantiate logger
47
gunicorn_logger = logging.getLogger('gunicorn.error')
48
app.logger.handlers = gunicorn_logger.handlers
49
app.logger.setLevel(gunicorn_logger.level)
50
51
return app
52
bp_bundle.py (blueprint):
JavaScript
1
20
20
1
import inspect
2
import pickle
3
4
from flask import current_app
5
from flask import render_template, Blueprint, session, url_for, request, redirect
6
from flask_login import login_required
7
8
from caffeine.main.forms import BundlePicker
9
from caffeine.models.models import BundleData, Clusterdata, AIQData
10
from caffeine.main.cluster import Cluster
11
from caffeine.utils.utils import get_session
12
from caffeine.utils.db_utils import populate_cluster_table
13
import caffeine.main.error as error
14
from caffeine.main.events import SliceRole
15
16
17
bundle = Blueprint('bp_bundle', __name__)
18
19
current_app.logger.error('hi')
20
stack trace:
JavaScript
1
37
37
1
Traceback (most recent call last):
2
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
3
worker.init_process()
4
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/workers/base.py", line 119, in init_process
5
self.load_wsgi()
6
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
7
self.wsgi = self.app.wsgi()
8
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi
9
self.callable = self.load()
10
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
11
return self.load_wsgiapp()
12
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
13
return util.import_app(self.app_uri)
14
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app
15
mod = importlib.import_module(module)
16
File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
17
return _bootstrap._gcd_import(name[level:], package, level)
18
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
19
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
20
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
21
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
22
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
23
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
24
File "/Users/aclinton/Documents/projects/caffeine/run.py", line 5, in <module>
25
app = create_app()
26
File "/Users/aclinton/Documents/projects/caffeine/caffeine/__init__.py", line 32, in create_app
27
from caffeine.routes.bp_bundle import bundle
28
File "/Users/aclinton/Documents/projects/caffeine/caffeine/routes/bp_bundle.py", line 19, in <module>
29
current_app.logger.error('hi')
30
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/werkzeug/local.py", line 347, in __getattr__
31
return getattr(self._get_current_object(), name)
32
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/werkzeug/local.py", line 306, in _get_current_object
33
return self.__local()
34
File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/flask/globals.py", line 52, in _find_app
35
raise RuntimeError(_app_ctx_err_msg)
36
RuntimeError: Working outside of application context.
37
Advertisement
Answer
When you import the module here from caffeine.routes.bp_bundle import bundle
the global statements at outermost sections will be executed. Now at this time the app is not running and this module is trying to use current_app
. Put this inside a route of Flask and it will work.