Skip to content
Advertisement

Flask – RuntimeError: Working outside of application context

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:

#! /usr/bin/python3.6
from caffeine import create_app
import os

app = create_app()

SECRET_KEY = b'x84xde=xc4x1c%rxf9Btxd3xcexc4oxaexf7'
app.secret_key = SECRET_KEY

if __name__ == '__main__':
    app.run(debug=False, host="0.0.0.0", port=8000)

init.py:

import os
import logging
from flask import session
from datetime import timedelta
from pathlib import Path
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from caffeine.config import Config

# Create db instance
db = SQLAlchemy()

# create login manager instance
login_manager = LoginManager()

def create_app():
    """
    Iinstantiates and initialize the Flask application
    """
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'bp_auth.login'
    login_manager.refresh_view = 'bp_auth.login'
    login_manager.login_message_category = 'info'

    # import Blueprint objects for routes
    from caffeine.routes.bp_aiq_bundle import main
    from caffeine.routes.bp_auth import auth
    from caffeine.routes.bp_bundle import bundle
    from caffeine.routes.bp_aiq import aiq
    from caffeine.errors.handlers import errors
    app.register_blueprint(main)
    app.register_blueprint(auth)
    app.register_blueprint(bundle)
    app.register_blueprint(aiq)
    app.register_blueprint(errors)

    @app.before_request
    def before_request():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(minutes=1440)

    # instantiate logger
    gunicorn_logger = logging.getLogger('gunicorn.error')
    app.logger.handlers = gunicorn_logger.handlers
    app.logger.setLevel(gunicorn_logger.level)

    return app

bp_bundle.py (blueprint):

import inspect
import pickle

from flask import current_app
from flask import render_template, Blueprint, session, url_for, request, redirect
from flask_login import login_required

from caffeine.main.forms import BundlePicker
from caffeine.models.models import BundleData, Clusterdata, AIQData
from caffeine.main.cluster import Cluster
from caffeine.utils.utils import get_session
from caffeine.utils.db_utils import populate_cluster_table
import caffeine.main.error as error
from caffeine.main.events import SliceRole


bundle = Blueprint('bp_bundle', __name__)

current_app.logger.error('hi')

stack trace:

Traceback (most recent call last):
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/workers/base.py", line 119, in init_process
    self.load_wsgi()
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
    return self.load_wsgiapp()
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app
    mod = importlib.import_module(module)
  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
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/Users/aclinton/Documents/projects/caffeine/run.py", line 5, in <module>
    app = create_app()
  File "/Users/aclinton/Documents/projects/caffeine/caffeine/__init__.py", line 32, in create_app
    from caffeine.routes.bp_bundle import bundle
  File "/Users/aclinton/Documents/projects/caffeine/caffeine/routes/bp_bundle.py", line 19, in <module>
    current_app.logger.error('hi')
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/Users/aclinton/Documents/environments/caff_env/lib/python3.9/site-packages/flask/globals.py", line 52, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement