title: Access Flask app context in CLI command
body: <p>I want to register a CLI command that's defined in a separate file from the Flask app factory. This command needs access to <code>app.config</code>. However, accessing <code>current_app.config</code> from the command raises <code>RuntimeError: Working outside of application context.</code></p>
  
  <p><code>app/__init__.py</code></p>
  
  <pre><code>from flask import Flask
  from app.commands import my_command
  
  def create_app():
      app = Flask(__name__, instance_relative_config=True)
      app.config.from_pyfile("config.py")
      app.add_command(my_command)
      return app
  </code></pre>
  
  <p><code>instance/config.py</code></p>
  
  <pre><code>TEST_VARIABLE = "TESTVALUE"
  </code></pre>
  
  <p><code>app/commands.py</code></p>
  
  <pre><code>from flask import current_app
  
  @click.command()
  def my_command():
      click.echo(current_app.config["TEST_VARIABLE"])
  </code></pre>
  
  <p>I expect running <code>flask my_command</code> to output <code>TESTVALUE</code>. However, I get the following error:</p>
  
  <pre><code>RuntimeError: Working outside of application context.
  
  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 app.app_context().  See the
  documentation for more information.
  </code></pre>
  
  <p>I need to use <code>with app.app_context():</code> for <code>current_app</code> to work, but I don't have access to <code>app</code> since it's defined in a factory. If I use <code>@app.cli.command()</code> in the factory, this would be no problem, as there I have access to the <code>app</code> variable, and wouldn't even need to push an app context.</p>
  
  <pre><code>def create_app():
      ...
      @app.cli.command()
      def my_command():
          click.echo(current_app.config["TEST_VARIABLE"])
      ...
  </code></pre>
  
  <p>However, I want to define my commands in other files and have them use values from the app config, while this requires all the commands to be nested in the factory function.</p>
  
  <p>I tried creating an app using the factory inside the command, and that worked, but I don't think doing that is a good idea just to have access to the config variables.</p>
  
  <pre><code>import click
  import app
  
  @click.command()
  def my_command():
      app_config = app.create_app().config
      click.echo(app_config["TEST_VARIABLE"])
  </code></pre>
  
  <p>How can I define a command that has access to the application context when using the application factory pattern?</p>