frogcdcn
frogcdcn

Reputation: 411

Using global variable with application context in flask

I defined a customized logger in mylogger.py, and the log dir is defined is config.py as LOG_DIR='/var/log'. In mylogger.py, the logger does some init work with LOG_DIR.

//mylogger.py
from flask import current_app
log_path = os.path.join(current_app.config['LOG_DIR'],"all.log") 
handler = logging.FileHandler(filename = logPath)
....

//config.py
LOG_DIR = "/var/log"

Flask says an error message:

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with modules.app_context().  See the
documentation for more information.

How could I use variable in config.py within app_context? Thank you.

Upvotes: 0

Views: 364

Answers (1)

joshua
joshua

Reputation: 335

def register_logging(app):
    log_path = os.path.join(app.config['LOG_DIR'],"all.log") 
    handler = logging.FileHandler(filename = logPath)

def create_app():
    app = Flask()
    register_logging(app)
    return app

app = create_app()

or just import config.py

from config import LOG_DIR

Upvotes: 1

Related Questions