Skip to content

click.get_current_context() returns None after reload #4460

@reubano

Description

@reubano

Following the guidelines in #3552, click.get_current_context() returns an empty ctx when the Flask app reloads (this is due to the thread switching).

app.py

from threading import get_native_id
from click import get_current_context

def create_app(*args, **kwargs):
    ctx = get_current_context(silent=True)
    print(get_native_id(), ctx)
    script_info = ctx.obj if ctx else None
    ...

manage.py

import click

from flask.cli import FlaskGroup, pass_script_info

from app import create_app


@click.group(cls=FlaskGroup, create_app=create_app)
@click.option("-m", "--config-mode", default="Development")
@pass_script_info
def manager(script_info, config_mode=None, **kwargs):
    script_info.config_mode = config_mode


if __name__ == "__main__":
    manager()
$ python manage.py run -p 5001
 * Environment: development
 * Debug mode: on
2537498, <click.core.Context object at 0x104a98490>
 * Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
 * Restarting with stat
2537262, None
 * Debugger is active!
 * Debugger PIN: 271-523-819

Notice how after Restarting with stat, ctx is now None.

Since passing script_info to the app factory was deprecated, the work-a-round should also work on app restarts just like the deprecated workflow does.

Environment:

  • Python version: 3.9.10
  • Flask version: 2.0.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions