Command Line Interface¶
Installing Flask installs theflask script, aClick command lineinterface, in your virtualenv. Executed from the terminal, this script givesaccess to built-in, extension, and application-defined commands. The--helpoption will give more information about any commands and options.
Application Discovery¶
Theflask command is installed by Flask, not your application; it must betold where to find your application in order to use it. The--appoption is used to specify how to load the application.
While--app supports a variety of options for specifying yourapplication, most use cases should be simple. Here are the typical values:
- (nothing)
The name “app” or “wsgi” is imported (as a “.py” file, or package),automatically detecting an app (
apporapplication) orfactory (create_appormake_app).--apphelloThe given name is imported, automatically detecting an app (
apporapplication) or factory (create_appormake_app).
--app has three parts: an optional path that sets the current workingdirectory, a Python file or dotted import path, and an optional variablename of the instance or factory. If the name is a factory, it can optionallybe followed by arguments in parentheses. The following values demonstrate theseparts:
--appsrc/helloSets the current working directory to
srcthen importshello.--apphello.webImports the path
hello.web.--apphello:app2Uses the
app2Flask instance inhello.--app'hello:create_app("dev")'The
create_appfactory inhellois called with the string'dev'as the argument.
If--app is not set, the command will try to import “app” or“wsgi” (as a “.py” file, or package) and try to detect an applicationinstance or factory.
Within the given import, the command looks for an application instance namedapp orapplication, then any application instance. If no instance isfound, the command looks for a factory function namedcreate_app ormake_app that returns an instance.
If parentheses follow the factory name, their contents are parsed asPython literals and passed as arguments and keyword arguments to thefunction. This means that strings must still be in quotes.
Run the Development Server¶
Therun command will start the development server. Itreplaces theFlask.run() method in most cases.
$ flask --app hello run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Warning
Do not use this command to run your application in production.Only use the development server during development. The development serveris provided for convenience, but is not designed to be particularly secure,stable, or efficient. SeeDeploying to Production for how to run in production.
If another program is already using port 5000, you’ll seeOSError:[Errno98] orOSError:[WinError10013] when theserver tries to start. SeeAddress already in use for how tohandle that.
Debug Mode¶
In debug mode, theflaskrun command will enable the interactive debugger and thereloader by default, and make errors easier to see and debug. To enable debug mode, usethe--debug option.
$flask--apphellorun--debug * Serving Flask app "hello" * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with inotify reloader * Debugger is active! * Debugger PIN: 223-456-919
The--debug option can also be passed to the top levelflask command to enabledebug mode for any command. The following tworun calls are equivalent.
$flask--apphello--debugrun$flask--apphellorun--debug
Watch and Ignore Files with the Reloader¶
When using debug mode, the reloader will trigger whenever your Python code or importedmodules change. The reloader can watch additional files with the--extra-filesoption. Multiple paths are separated with:, or; on Windows.
$ flask run --extra-files file1:dirA/file2:dirB/ * Running on http://127.0.0.1:8000/ * Detected change in '/path/to/file1', reloading
The reloader can also ignore files usingfnmatch patterns with the--exclude-patterns option. Multiple patterns are separated with:, or; onWindows.
Open a Shell¶
To explore the data in your application, you can start an interactive Pythonshell with theshell command. An applicationcontext will be active, and the app instance will be imported.
$ flask shellPython 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linuxApp: example [production]Instance: /home/david/Projects/pallets/flask/instance>>>
Useshell_context_processor() to add other automatic imports.
Environment Variables From dotenv¶
Theflask command supports setting any option for any command withenvironment variables. The variables are named likeFLASK_OPTION orFLASK_COMMAND_OPTION, for exampleFLASK_APP orFLASK_RUN_PORT.
Rather than passing options every time you run a command, or environmentvariables every time you open a new terminal, you can use Flask’s dotenvsupport to set environment variables automatically.
Ifpython-dotenv is installed, running theflask command will setenvironment variables defined in the files.env and.flaskenv.You can also specify an extra file to load with the--env-fileoption. Dotenv files can be used to avoid having to set--app orFLASK_APP manually, and to set configuration using environmentvariables similar to how some deployment services work.
Variables set on the command line are used over those set in.env,which are used over those set in.flaskenv..flaskenv should beused for public variables, such asFLASK_APP, while.env should notbe committed to your repository so that it can set private variables.
Directories are scanned upwards from the directory you callflaskfrom to locate the files.
The files are only loaded by theflask command or callingrun(). If you would like to load these files when running inproduction, you should callload_dotenv() manually.
Setting Command Options¶
Click is configured to load default values for command options fromenvironment variables. The variables use the patternFLASK_COMMAND_OPTION. For example, to set the port for the runcommand, instead offlaskrun--port8000:
$ export FLASK_RUN_PORT=8000$ flask run * Running on http://127.0.0.1:8000/
$ set -x FLASK_RUN_PORT 8000$ flask run * Running on http://127.0.0.1:8000/
> set FLASK_RUN_PORT=8000> flask run * Running on http://127.0.0.1:8000/
> $env:FLASK_RUN_PORT = 8000> flask run * Running on http://127.0.0.1:8000/
These can be added to the.flaskenv file just likeFLASK_APP tocontrol default command options.
Disable dotenv¶
Theflask command will show a message if it detects dotenv files butpython-dotenv is not installed.
$flaskrun*Tip:Thereare.envfilespresent.Do"pip install python-dotenv"tousethem.You can tell Flask not to load dotenv files even when python-dotenv isinstalled by setting theFLASK_SKIP_DOTENV environment variable.This can be useful if you want to load them manually, or if you’re usinga project runner that loads them already. Keep in mind that theenvironment variables must be set before the app loads or it won’tconfigure as expected.
$ export FLASK_SKIP_DOTENV=1$ flask run
$ set -x FLASK_SKIP_DOTENV 1$ flask run
> set FLASK_SKIP_DOTENV=1> flask run
> $env:FLASK_SKIP_DOTENV = 1> flask run
Environment Variables From virtualenv¶
If you do not want to install dotenv support, you can still set environmentvariables by adding them to the end of the virtualenv’sactivatescript. Activating the virtualenv will set the variables.
Unix Bash,.venv/bin/activate:
$ export FLASK_APP=hello
Fish,.venv/bin/activate.fish:
$ set -x FLASK_APP hello
Windows CMD,.venv\Scripts\activate.bat:
>setFLASK_APP=hello
Windows Powershell,.venv\Scripts\activate.ps1:
> $env:FLASK_APP = "hello"
It is preferred to use dotenv support over this, since.flaskenv can becommitted to the repository so that it works automatically wherever the projectis checked out.
Custom Commands¶
Theflask command is implemented usingClick. See that project’sdocumentation for full information about writing commands.
This example adds the commandcreate-user that takes the argumentname.
importclickfromflaskimportFlaskapp=Flask(__name__)@app.cli.command("create-user")@click.argument("name")defcreate_user(name):...
$ flask create-user admin
This example adds the same command, but asusercreate, a command in agroup. This is useful if you want to organize multiple related commands.
importclickfromflaskimportFlaskfromflask.cliimportAppGroupapp=Flask(__name__)user_cli=AppGroup('user')@user_cli.command('create')@click.argument('name')defcreate_user(name):...app.cli.add_command(user_cli)
$ flask user create demo
SeeRunning Commands with the CLI Runner for an overview of how to test your customcommands.
Registering Commands with Blueprints¶
If your application uses blueprints, you can optionally register CLIcommands directly onto them. When your blueprint is registered onto yourapplication, the associated commands will be available to theflaskcommand. By default, those commands will be nested in a group matchingthe name of the blueprint.
fromflaskimportBlueprintbp=Blueprint('students',__name__)@bp.cli.command('create')@click.argument('name')defcreate(name):...app.register_blueprint(bp)
$ flask students create alice
You can alter the group name by specifying thecli_group parameterwhen creating theBlueprint object, or later withapp.register_blueprint(bp,cli_group='...').The following are equivalent:
bp=Blueprint('students',__name__,cli_group='other')# orapp.register_blueprint(bp,cli_group='other')
$ flask other create alice
Specifyingcli_group=None will remove the nesting and merge thecommands directly to the application’s level:
bp=Blueprint('students',__name__,cli_group=None)# orapp.register_blueprint(bp,cli_group=None)
$ flask create alice
Application Context¶
Commands added using the Flask app’scli orFlaskGroupcommand() decoratorwill be executed with an application context pushed, so your customcommands and parameters have access to the app and its configuration. Thewith_appcontext() decorator can be used to get the samebehavior, but is not needed in most cases.
importclickfromflask.cliimportwith_appcontext@click.command()@with_appcontextdefdo_work():...app.cli.add_command(do_work)
Plugins¶
Flask will automatically load commands specified in theflask.commandsentry point. This is useful for extensions that want to add commands whenthey are installed. Entry points are specified inpyproject.toml:
[project.entry-points."flask.commands"]my-command="my_extension.commands:cli"
Insidemy_extension/commands.py you can then export a Clickobject:
importclick@click.command()defcli():...
Once that package is installed in the same virtualenv as your Flask project,you can runflaskmy-command to invoke the command.
Custom Scripts¶
When you are using the app factory pattern, it may be more convenient to defineyour own Click script. Instead of using--app and letting Flask loadyour application, you can create your own Click object and export it as aconsole script entry point.
Create an instance ofFlaskGroup and pass it the factory:
importclickfromflaskimportFlaskfromflask.cliimportFlaskGroupdefcreate_app():app=Flask('wiki')# other setupreturnapp@click.group(cls=FlaskGroup,create_app=create_app)defcli():"""Management script for the Wiki application."""
Define the entry point inpyproject.toml:
[project.scripts]wiki="wiki:cli"
Install the application in the virtualenv in editable mode and the customscript is available. Note that you don’t need to set--app.
$ pip install -e .$ wiki run
Errors in Custom Scripts
When using a custom script, if you introduce an error in yourmodule-level code, the reloader will fail because it can no longerload the entry point.
Theflask command, being separate from your code, does not havethis issue and is recommended in most cases.
PyCharm Integration¶
PyCharm Professional provides a special Flask run configuration to run the developmentserver. For the Community Edition, and for other commands besidesrun, you need tocreate a custom run configuration. These instructions should be similar for any otherIDE you use.
In PyCharm, with your project open, click onRun from the menu bar and go toEditConfigurations. You’ll see a screen similar to this:

Once you create a configuration for theflaskrun, you can copy and change it tocall any other command.
Click the+ (Add New Configuration) button and selectPython. Give the configurationa name such as “flask run”.
Click theScript path dropdown and change it toModule name, then inputflask.
TheParameters field is set to the CLI command to execute along with any arguments.This example uses--apphellorun--debug, which will run the development server indebug mode.--apphello should be the import or file with your Flask app.
If you installed your project as a package in your virtualenv, you may uncheck thePYTHONPATH options. This will more accurately match how you deploy later.
ClickOK to save and close the configuration. Select the configuration in the mainPyCharm window and click the play button next to it to run the server.
Now that you have a configuration forflaskrun, you can copy that configuration andchange theParameters argument to run a different CLI command.