Attributes of flask.g not exist in cli command with app context

Viewed 29

I use flask app factory:

app.py

from flask import Flask, g

from . import commands
from .database import DatabaseManager
from .extensions import db
from .settings import ProdConfig


def create_app(config_object=ProdConfig):
    '''Flask app factory'''
    app = Flask(__name__)
    app.url_map.strict_slashes = False
    app.config.from_object(config_object)

    register_extensions(app)
    register_blueprints(app)
    register_commands(app)

    @app.before_request
    def create_context():
        g.db = db.database
        g.db_manager = DatabaseManager()

    return app

# Another functions
# ...

def register_commands(app):
    app.cli.add_command(commands.root_group)

Then i wrote command in:

commands.py

from flask import g
from flask.cli import AppGroup

root_group = AppGroup('myapp')

@root_group.command('test')
def test():
    print(g.db)

Then when i run command flask myapp test i get AttributeError on g.db. So somehow flask.g dont receive attrs g.db and g.db_manager initialized in before_request. As i understand it have to receive, because app_context must be pushed when cli command based on AppGroup runs. How to fix this?

1 Answers

From testing i understand that when CLI command executes, Flask not push Request context, so @before_request hook not executes. I dont find good way to push Request context in my cli command and make this hack:

@root_group.command()
def test():
    exec_before_request_hooks()
    print(g.db_manager)



# HACK: run @app.before_request for CLI command
def exec_before_request_hooks():
    current_app.test_client().get()

If anybody know better solution, i will be very appreciate to hear it)

Related