Skip to content
Myr

Merge pull request #4646 from pallets/cli-app-env

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by GitHub · parents fe4003b, ab1fbef · Browse files · 18 files+343 added−633 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

18 files+343 added−633 removed

  • tests:+1 added−0 removed
  • other:+342 added−633 removed

18 files+343 added−633 removed

modified:docs/patterns/appfactories.rst+9 added-60 removed
87 unmodified lines
88------------------8990To run such an application, you can use the :command:`flask` command:9192.. tabs::92.. code-block:: text9394 .. group-tab:: Bash94 $ flask run --app hello run9596 .. code-block:: text96Flask will automatically detect the factory if it is named97``create_app`` or ``make_app`` in ``hello``. You can also pass arguments98to the factory like this:9998 $ export FLASK_APP=myapp99 $ flask run100.. code-block:: text101101 .. group-tab:: Fish102 $ flask run --app hello:create_app(local_auth=True)``103103 .. code-block:: text104Then the ``create_app`` factory in ``myapp`` is called with the keyword105argument ``local_auth=True``. See :doc:`/cli` for more detail.106105 $ set -x FLASK_APP myapp106 $ flask run107108 .. group-tab:: CMD109110 .. code-block:: text111112 > set FLASK_APP=myapp113 > flask run114115 .. group-tab:: Powershell116117 .. code-block:: text118119 > $env:FLASK_APP = "myapp"120 > flask run121122Flask will automatically detect the factory (``create_app`` or ``make_app``)123in ``myapp``. You can also pass arguments to the factory like this:124125.. tabs::126127 .. group-tab:: Bash128129 .. code-block:: text130131 $ export FLASK_APP="myapp:create_app('dev')"132 $ flask run133134 .. group-tab:: Fish135136 .. code-block:: text137138 $ set -x FLASK_APP "myapp:create_app('dev')"139 $ flask run140141 .. group-tab:: CMD142143 .. code-block:: text144145 > set FLASK_APP="myapp:create_app('dev')"146 > flask run147148 .. group-tab:: Powershell149150 .. code-block:: text151152 > $env:FLASK_APP = "myapp:create_app('dev')"153 > flask run154155Then the ``create_app`` factory in ``myapp`` is called with the string156``'dev'`` as the argument. See :doc:`/cli` for more detail.157107Factory Improvements108--------------------109110The factory function above is not very clever, but you can improve it.
8 unmodified lines
modified:docs/patterns/packages.rst+7 added-60 removed
54 unmodified lines
55 'flask',56 ],57 )5859In order to run the application you need to export an environment variable60that tells Flask where to find the application instance:59Install your application so it is importable:6062.. tabs::61.. code-block:: text6264 .. group-tab:: Bash63 $ pip install -e .6466 .. code-block:: text65To use the ``flask`` command and run your application you need to set66the ``--app`` option that tells Flask where to find the application67instance:6868 $ export FLASK_APP=yourapplication69 $ flask --app yourapplication run7070 .. group-tab:: Fish7172 .. code-block:: text7374 $ set -x FLASK_APP yourapplication7576 .. group-tab:: CMD7778 .. code-block:: text7980 > set FLASK_APP=yourapplication8182 .. group-tab:: Powershell8384 .. code-block:: text8586 > $env:FLASK_APP = "yourapplication"8788If you are outside of the project directory make sure to provide the exact89path to your application directory. Similarly you can turn on the90development features like this:9192.. tabs::9394 .. group-tab:: Bash9596 .. code-block:: text9798 $ export FLASK_ENV=development99100 .. group-tab:: Fish101102 .. code-block:: text103104 $ set -x FLASK_ENV development105106 .. group-tab:: CMD107108 .. code-block:: text109110 > set FLASK_ENV=development111112 .. group-tab:: Powershell113114 .. code-block:: text115116 > $env:FLASK_ENV = "development"117118In order to install and run the application you need to issue the following119commands::120121 $ pip install -e .122 $ flask run12371What did we gain from this? Now we can restructure the application a bit72into multiple modules. The only thing you have to remember is the73following quick checklist:74
56 unmodified lines
modified:docs/tutorial/database.rst+2 added-4 removed
194 unmodified lines
195196 If you're still running the server from the previous page, you can197 either stop the server, or run this command in a new terminal. If198 you use a new terminal, remember to change to your project directory199 and activate the env as described in :doc:`/installation`. You'll200 also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on the201 previous page.199 and activate the env as described in :doc:`/installation`.200201Run the ``init-db`` command:202203.. code-block:: none204207 $ flask init-db205 $ flask --app flaskr init-db206 Initialized the database.207208There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in209your project.
2 unmodified lines
modified:docs/tutorial/deploy.rst+3 added-29 removed
46 unmodified lines
4748Since this is a different machine, you need to run ``init-db`` again to49create the database in the instance folder.5051.. tabs::51 .. code-block:: text5253 .. group-tab:: Bash53 $ flask --app flaskr init-db5455 .. code-block:: text5657 $ export FLASK_APP=flaskr58 $ flask init-db5960 .. group-tab:: Fish6162 .. code-block:: text6364 $ set -x FLASK_APP flaskr65 $ flask init-db6667 .. group-tab:: CMD6869 .. code-block:: text7071 > set FLASK_APP=flaskr72 > flask init-db7374 .. group-tab:: Powershell7576 .. code-block:: text7778 > $env:FLASK_APP = "flaskr"79 > flask init-db8055When Flask detects that it's installed (not in editable mode), it uses56a different directory for the instance folder. You can find it at57``venv/var/flaskr-instance`` instead.58
41 unmodified lines
100101 $ pip install waitress102103You need to tell Waitress about your application, but it doesn't use130``FLASK_APP`` like ``flask run`` does. You need to tell it to import and104``--app`` like ``flask run`` does. You need to tell it to import and105call the application factory to get an application object.106107.. code-block:: none108
12 unmodified lines
modified:docs/tutorial/factory.rst+4 added-34 removed
133 unmodified lines
134exception, and restarts the server whenever you make changes to the135code. You can leave it running and just reload the browser page as you136follow the tutorial.137138.. tabs::138.. code-block:: text139140 .. group-tab:: Bash140 $ flask --app flaskr --env development run141142 .. code-block:: text143144 $ export FLASK_APP=flaskr145 $ export FLASK_ENV=development146 $ flask run147148 .. group-tab:: Fish149150 .. code-block:: text151152 $ set -x FLASK_APP flaskr153 $ set -x FLASK_ENV development154 $ flask run155156 .. group-tab:: CMD157158 .. code-block:: text159160 > set FLASK_APP=flaskr161 > set FLASK_ENV=development162 > flask run163164 .. group-tab:: Powershell165166 .. code-block:: text167168 > $env:FLASK_APP = "flaskr"169 > $env:FLASK_ENV = "development"170 > flask run171142You'll see output similar to this:143174.. code-block:: none144.. code-block:: text145146 * Serving Flask app "flaskr"147 * Environment: development148 * Debug mode: on149 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)150 * Restarting with stat151 * Debugger is active!182 * Debugger PIN: 855-212-761152 * Debugger PIN: nnn-nnn-nnn153154Visit http://127.0.0.1:5000/hello in a browser and you should see the155"Hello, World!" message. Congratulations, you're now running your Flask156web application!
7 unmodified lines
modified:docs/tutorial/install.rst+1 added-1 removed
107 unmodified lines
108 Werkzeug 0.14.1109 wheel 0.30.0110111Nothing changes from how you've been running your project so far.112``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs112``--app`` is still set to ``flaskr`` and ``flask run`` still runs113the application, but you can call it from anywhere, not just the114``flask-tutorial`` directory.115116Continue to :doc:`tests`.
modified:docs/cli.rst+48 added-158 removed
13 unmodified lines
14Application Discovery15---------------------1617The ``flask`` command is installed by Flask, not your application; it must be18told where to find your application in order to use it. The ``FLASK_APP``19environment variable is used to specify how to load the application.18told where to find your application in order to use it. The ``--app``19option is used to specify how to load the application.2021.. tabs::2223 .. group-tab:: Bash2425 .. code-block:: text2627 $ export FLASK_APP=hello28 $ flask run2930 .. group-tab:: Fish3132 .. code-block:: text3334 $ set -x FLASK_APP hello35 $ flask run3637 .. group-tab:: CMD3839 .. code-block:: text4041 > set FLASK_APP=hello42 > flask run4344 .. group-tab:: Powershell4546 .. code-block:: text4748 > $env:FLASK_APP = "hello"49 > flask run5051While ``FLASK_APP`` supports a variety of options for specifying your21While ``--app`` supports a variety of options for specifying your22application, most use cases should be simple. Here are the typical values:2324(nothing)25 The name "app" or "wsgi" is imported (as a ".py" file, or package),26 automatically detecting an app (``app`` or ``application``) or27 factory (``create_app`` or ``make_app``).2859``FLASK_APP=hello``29``--app hello``30 The given name is imported, automatically detecting an app (``app``31 or ``application``) or factory (``create_app`` or ``make_app``).3233----3465``FLASK_APP`` has three parts: an optional path that sets the current working35``--app`` has three parts: an optional path that sets the current working36directory, a Python file or dotted import path, and an optional variable37name of the instance or factory. If the name is a factory, it can optionally38be followed by arguments in parentheses. The following values demonstrate these39parts:4071``FLASK_APP=src/hello``41``--app src/hello``42 Sets the current working directory to ``src`` then imports ``hello``.4374``FLASK_APP=hello.web``44``--app hello.web``45 Imports the path ``hello.web``.4677``FLASK_APP=hello:app2``47``--app hello:app2``48 Uses the ``app2`` Flask instance in ``hello``.4980``FLASK_APP="hello:create_app('dev')"``50``--app 'hello:create_app("dev")'``51 The ``create_app`` factory in ``hello`` is called with the string ``'dev'``52 as the argument.5384If ``FLASK_APP`` is not set, the command will try to import "app" or54If ``--app`` is not set, the command will try to import "app" or55"wsgi" (as a ".py" file, or package) and try to detect an application56instance or factory.5758Within the given import, the command looks for an application instance named
47 unmodified lines
106------------107108.. versionadded:: 1.0109140The environment in which the Flask app runs is set by the141:envvar:`FLASK_ENV` environment variable. If not set it defaults to110The environment in which the Flask app executes is set by the111``FLASK_ENV`` environment variable. When using the ``flask`` command, it112can also be set with the ``--env`` option. If not set it defaults to113``production``. The other recognized environment is ``development``.114Flask and extensions may choose to enable behaviors based on the115environment.116117If the env is set to ``development``, the ``flask`` command will enable118debug mode and ``flask run`` will enable the interactive debugger and119reloader.120150.. tabs::121.. code-block:: text122152 .. group-tab:: Bash123 $ flask --app hello --env development run124 * Serving Flask app "hello"125 * Environment: development126 * Debug mode: on127 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)128 * Restarting with inotify reloader129 * Debugger is active!130 * Debugger PIN: 223-456-919131154 .. code-block:: text132156 $ export FLASK_ENV=development157 $ flask run158 * Serving Flask app "hello"159 * Environment: development160 * Debug mode: on161 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)162 * Restarting with inotify reloader163 * Debugger is active!164 * Debugger PIN: 223-456-919165166 .. group-tab:: Fish167168 .. code-block:: text169170 $ set -x FLASK_ENV development171 $ flask run172 * Serving Flask app "hello"173 * Environment: development174 * Debug mode: on175 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)176 * Restarting with inotify reloader177 * Debugger is active!178 * Debugger PIN: 223-456-919179180 .. group-tab:: CMD181182 .. code-block:: text183184 > set FLASK_ENV=development185 > flask run186 * Serving Flask app "hello"187 * Environment: development188 * Debug mode: on189 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)190 * Restarting with inotify reloader191 * Debugger is active!192 * Debugger PIN: 223-456-919193194 .. group-tab:: Powershell195196 .. code-block:: text197198 > $env:FLASK_ENV = "development"199 > flask run200 * Serving Flask app "hello"201 * Environment: development202 * Debug mode: on203 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)204 * Restarting with inotify reloader205 * Debugger is active!206 * Debugger PIN: 223-456-919207208133Watch Extra Files with the Reloader134~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~135136When using development mode, the reloader will trigger whenever your137Python code or imported modules change. The reloader can watch214additional files with the ``--extra-files`` option, or the215``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are138additional files with the ``--extra-files`` option. Multiple paths are139separated with ``:``, or ``;`` on Windows.140218.. tabs::141.. code-block:: text142220 .. group-tab:: Bash143 $ flask run --extra-files file1:dirA/file2:dirB/144 * Running on http://127.0.0.1:8000/145 * Detected change in '/path/to/file1', reloading146222 .. code-block:: text147224 $ flask run --extra-files file1:dirA/file2:dirB/225 # or226 $ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/227 $ flask run228 * Running on http://127.0.0.1:8000/229 * Detected change in '/path/to/file1', reloading230231 .. group-tab:: Fish232233 .. code-block:: text234235 $ flask run --extra-files file1:dirA/file2:dirB/236 # or237 $ set -x FLASK_RUN_EXTRA_FILES file1 dirA/file2 dirB/238 $ flask run239 * Running on http://127.0.0.1:8000/240 * Detected change in '/path/to/file1', reloading241242 .. group-tab:: CMD243244 .. code-block:: text245246 > flask run --extra-files file1:dirA/file2:dirB/247 # or248 > set FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/249 > flask run250 * Running on http://127.0.0.1:8000/251 * Detected change in '/path/to/file1', reloading252253 .. group-tab:: Powershell254255 .. code-block:: text256257 > flask run --extra-files file1:dirA/file2:dirB/258 # or259 > $env:FLASK_RUN_EXTRA_FILES = "file1:dirA/file2:dirB/"260 > flask run261 * Running on http://127.0.0.1:8000/262 * Detected change in '/path/to/file1', reloading263264148Ignore files with the Reloader149~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~150151The reloader can also ignore files using :mod:`fnmatch` patterns with269the ``--exclude-patterns`` option, or the ``FLASK_RUN_EXCLUDE_PATTERNS``270environment variable. Multiple patterns are separated with ``:``, or271``;`` on Windows.152the ``--exclude-patterns`` option. Multiple patterns are separated with153``:``, or ``;`` on Windows.154155156Debug Mode157----------158277Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``,278as described above. If you want to control debug mode separately, use279:envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.159Debug mode will be enabled when the execution environment is160``development``, as described above. If you want to control debug mode161separately, use the ``--debug/--no-debug`` option or the ``FLASK_DEBUG``162environment variable.163164165.. _dotenv:166167Environment Variables From dotenv168---------------------------------169287Rather than setting ``FLASK_APP`` each time you open a new terminal, you can288use Flask's dotenv support to set environment variables automatically.170The ``flask`` command supports setting any option for any command with171environment variables. The variables are named like ``FLASK_OPTION`` or172``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or173``FLASK_RUN_PORT``.174175Rather than passing options every time you run a command, or environment176variables every time you open a new terminal, you can use Flask's dotenv177support to set environment variables automatically.178179If `python-dotenv`_ is installed, running the ``flask`` command will set291environment variables defined in the files :file:`.env` and :file:`.flaskenv`.292This can be used to avoid having to set ``FLASK_APP`` manually every time you293open a new terminal, and to set configuration using environment variables294similar to how some deployment services work.180environment variables defined in the files ``.env`` and ``.flaskenv``.181You can also specify an extra file to load with the ``--env-file``182option. Dotenv files can be used to avoid having to set ``--app`` or183``FLASK_APP`` manually, and to set configuration using environment184variables similar to how some deployment services work.185186Variables set on the command line are used over those set in :file:`.env`,187which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be188used for public variables, such as ``FLASK_APP``, while :file:`.env` should not
312 unmodified lines
501Custom Scripts502--------------503504When you are using the app factory pattern, it may be more convenient to define615your own Click script. Instead of using ``FLASK_APP`` and letting Flask load505your own Click script. Instead of using ``--app`` and letting Flask load506your application, you can create your own Click object and export it as a507`console script`_ entry point.508509Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::
25 unmodified lines
535 },536 )537538Install the application in the virtualenv in editable mode and the custom649script is available. Note that you don't need to set ``FLASK_APP``. ::539script is available. Note that you don't need to set ``--app``. ::540541 $ pip install -e .542 $ wiki run543
65 unmodified lines
modified:docs/config.rst+20 added-48 removed
45 unmodified lines
46------------------------------4748The :data:`ENV` and :data:`DEBUG` config values are special because they49may behave inconsistently if changed after the app has begun setting up.50In order to set the environment and debug mode reliably, Flask uses51environment variables.50In order to set the environment and debug mode reliably, pass options to51the ``flask`` command or use environment variables.5253The environment is used to indicate to Flask, extensions, and other54programs, like Sentry, what context Flask is running in. It is55controlled with the :envvar:`FLASK_ENV` environment variable and56defaults to ``production``.53The execution environment is used to indicate to Flask, extensions, and54other programs, like Sentry, what context Flask is running in. It is55controlled with the ``FLASK_ENV`` environment variable, or the56``--env`` option when using the ``flask`` command, and defaults to57``production``.5858Setting :envvar:`FLASK_ENV` to ``development`` will enable debug mode.59``flask run`` will use the interactive debugger and reloader by default60in debug mode. To control this separately from the environment, use the61:envvar:`FLASK_DEBUG` flag.59Setting ``--env development`` will enable debug mode. ``flask run`` will60use the interactive debugger and reloader by default in debug mode. To61control this separately from the environment, use the62``--debug/--no-debug`` option or the ``FLASK_DEBUG`` environment63variable.6463.. versionchanged:: 1.064 Added :envvar:`FLASK_ENV` to control the environment separately65 from debug mode. The development environment enables debug mode.6665To switch Flask to the development environment and enable debug mode,68set :envvar:`FLASK_ENV`:66set ``--env``:6770.. tabs::68.. code-block:: text6972 .. group-tab:: Bash70 $ flask --app hello --env development run7174 .. code-block:: text72Using the options or environment variables as described above is73recommended. While it is possible to set :data:`ENV` and :data:`DEBUG`74in your config or code, this is strongly discouraged. They can't be read75early by the ``flask`` command, and some systems or extensions may have76already configured themselves based on a previous value.7776 $ export FLASK_ENV=development77 $ flask run7879 .. group-tab:: Fish8081 .. code-block:: text8283 $ set -x FLASK_ENV development84 $ flask run8586 .. group-tab:: CMD8788 .. code-block:: text8990 > set FLASK_ENV=development91 > flask run9293 .. group-tab:: Powershell9495 .. code-block:: text9697 > $env:FLASK_ENV = "development"98 > flask run99100Using the environment variables as described above is recommended. While101it is possible to set :data:`ENV` and :data:`DEBUG` in your config or102code, this is strongly discouraged. They can't be read early by the103``flask`` command, and some systems or extensions may have already104configured themselves based on a previous value.10510679Builtin Configuration Values80----------------------------8182The following configuration values are used internally by Flask:
704 unmodified lines
modified:docs/debugging.rst+11 added-65 removed
37 unmodified lines
38 browser. It is protected by a pin, but still represents a major39 security risk. Do not run the development server or debugger in a40 production environment.4142To enable the debugger, run the development server with the43``FLASK_ENV`` environment variable set to ``development``. This puts44Flask in debug mode, which changes how it handles some errors, and45enables the debugger and reloader.42To enable the debugger, run the development server with the environment43set to ``development``. This puts Flask in debug mode, which changes how44it handles some errors, and enables the debugger and reloader.4547.. tabs::46.. code-block:: text4749 .. group-tab:: Bash48 $ flask --app hello --env development run4951 .. code-block:: text5253 $ export FLASK_ENV=development54 $ flask run5556 .. group-tab:: Fish5758 .. code-block:: text5960 $ set -x FLASK_ENV development61 $ flask run6263 .. group-tab:: CMD6465 .. code-block:: text6667 > set FLASK_ENV=development68 > flask run6970 .. group-tab:: Powershell7172 .. code-block:: text7374 > $env:FLASK_ENV = "development"75 > flask run7677``FLASK_ENV`` can only be set as an environment variable. When running50``FLASK_ENV`` can also be set as an environment variable. When running51from Python code, passing ``debug=True`` enables debug mode, which is79mostly equivalent. Debug mode can be controlled separately from80``FLASK_ENV`` with the ``FLASK_DEBUG`` environment variable as well.52mostly equivalent. Debug mode can be controlled separately from the53environment with the ``--debug/--no-debug`` option or the54``FLASK_DEBUG`` environment variable.5556.. code-block:: python5758 app.run(debug=True)
16 unmodified lines
75When using an external debugger, the app should still be in debug mode,76but it can be useful to disable the built-in debugger and reloader,77which can interfere.78105When running from the command line:79.. code-block:: text80107.. tabs::81 $ flask --app hello --env development run --no-debugger --no-reload82109 .. group-tab:: Bash110111 .. code-block:: text112113 $ export FLASK_ENV=development114 $ flask run --no-debugger --no-reload115116 .. group-tab:: Fish117118 .. code-block:: text119120 $ set -x FLASK_ENV development121 $ flask run --no-debugger --no-reload122123 .. group-tab:: CMD124125 .. code-block:: text126127 > set FLASK_ENV=development128 > flask run --no-debugger --no-reload129130 .. group-tab:: Powershell131132 .. code-block:: text133134 > $env:FLASK_ENV = "development"135 > flask run --no-debugger --no-reload13683When running from Python:8485.. code-block:: python86
7 unmodified lines
modified:docs/quickstart.rst+19 added-96 removed
37 unmodified lines
38Save it as :file:`hello.py` or something similar. Make sure to not call39your application :file:`flask.py` because this would conflict with Flask40itself.4142To run the application, use the :command:`flask` command or43:command:`python -m flask`. Before you can do that you need44to tell your terminal the application to work with by exporting the45``FLASK_APP`` environment variable:42To run the application, use the ``flask`` command or43``python -m flask``. You need to tell the Flask where your application44is with the ``-app`` option.4547.. tabs::46.. code-block:: text4749 .. group-tab:: Bash48 $ flask --app hello run49 * Serving Flask app 'hello' (lazy loading)50 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)5151 .. code-block:: text5253 $ export FLASK_APP=hello54 $ flask run55 * Running on http://127.0.0.1:5000/5657 .. group-tab:: Fish5859 .. code-block:: text6061 $ set -x FLASK_APP hello62 $ flask run63 * Running on http://127.0.0.1:5000/6465 .. group-tab:: CMD6667 .. code-block:: text6869 > set FLASK_APP=hello70 > flask run71 * Running on http://127.0.0.1:5000/7273 .. group-tab:: Powershell7475 .. code-block:: text7677 > $env:FLASK_APP = "hello"78 > flask run79 * Running on http://127.0.0.1:5000/8052.. admonition:: Application Discovery Behavior5354 As a shortcut, if the file is named ``app.py`` or ``wsgi.py``, you84 don't have to set the ``FLASK_APP`` environment variable. See85 :doc:`/cli` for more details.55 don't have to use ``--app``. See :doc:`/cli` for more details.5657This launches a very simple builtin server, which is good enough for58testing but probably not what you want to use in production. For59deployment options see :doc:`deploying/index`.
23 unmodified lines
8384 This tells your operating system to listen on all public IPs.8586117What to do if the Server does not Start118---------------------------------------119120In case the :command:`python -m flask` fails or :command:`flask`121does not exist, there are multiple reasons this might be the case.122First of all you need to look at the error message.123124Old Version of Flask125````````````````````126127Versions of Flask older than 0.11 used to have different ways to start the128application. In short, the :command:`flask` command did not exist, and129neither did :command:`python -m flask`. In that case you have two options:130either upgrade to newer Flask versions or have a look at :doc:`/server`131to see the alternative method for running a server.132133Invalid Import Name134```````````````````135136The ``FLASK_APP`` environment variable is the name of the module to import at137:command:`flask run`. In case that module is incorrectly named you will get an138import error upon start (or if debug is enabled when you navigate to the139application). It will tell you what it tried to import and why it failed.140141The most common reason is a typo or because you did not actually create an142``app`` object.14314487Debug Mode88----------8990The ``flask run`` command can do more than just start the development
12 unmodified lines
103 browser. It is protected by a pin, but still represents a major104 security risk. Do not run the development server or debugger in a105 production environment.106165To enable all development features, set the ``FLASK_ENV`` environment166variable to ``development`` before calling ``flask run``.107To enable all development features, set the ``--env`` option to108``development``.109168.. tabs::110.. code-block:: text111170 .. group-tab:: Bash112 $ flask --app hello --env development run113 * Serving Flask app 'hello' (lazy loading)114 * Environment: development115 * Debug mode: on116 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)117 * Restarting with stat118 * Debugger is active!119 * Debugger PIN: nnn-nnn-nnn120172 .. code-block:: text173174 $ export FLASK_ENV=development175 $ flask run176177 .. group-tab:: Fish178179 .. code-block:: text180181 $ set -x FLASK_ENV development182 $ flask run183184 .. group-tab:: CMD185186 .. code-block:: text187188 > set FLASK_ENV=development189 > flask run190191 .. group-tab:: Powershell192193 .. code-block:: text194195 > $env:FLASK_ENV = "development"196 > flask run197121See also:122123- :doc:`/server` and :doc:`/cli` for information about running in124 development mode.
757 unmodified lines
modified:docs/reqcontext.rst+2 added-2 removed
225 unmodified lines
226associated with it is destroyed. If an error occurs during development,227it is useful to delay destroying the data for debugging purposes.228229When the development server is running in development mode (the230``FLASK_ENV`` environment variable is set to ``'development'``), the231error and data will be preserved and shown in the interactive debugger.230``--env`` option is set to ``'development'``), the error and data will231be preserved and shown in the interactive debugger.232233This behavior can be controlled with the234:data:`PRESERVE_CONTEXT_ON_EXCEPTION` config. As described above, it235defaults to ``True`` in the development environment.
30 unmodified lines
modified:docs/server.rst+15 added-8 removed
17 unmodified lines
18Command Line19------------2021The ``flask run`` command line script is the recommended way to run the22development server. It requires setting the ``FLASK_APP`` environment23variable to point to your application, and ``FLASK_ENV=development`` to24fully enable development mode.22development server. Use the ``--app`` option to point to your23application, and the ``--env development`` option to fully enable24development mode.2526.. code-block:: text2728 $ flask --app hello --env development run2930These options (and any others) can also be set using environment31variables.3233.. tabs::3435 .. group-tab:: Bash36
34 unmodified lines
71and using the CLI.7273.. note::7468 Prior to Flask 1.0 the ``FLASK_ENV`` environment variable was not69 supported and you needed to enable debug mode by exporting70 ``FLASK_DEBUG=1``. This can still be used to control debug mode, but71 you should prefer setting the development environment as shown72 above.75 Debug mode can be controlled separately from the development76 environment with the ``--debug/--no-debug`` option or the77 ``FLASK_DEBUG`` environment variable. This is how older versions of78 Flask worked. You should prefer setting the development environment79 as shown above.808182.. _address-already-in-use:83
89 unmodified lines
modified:examples/javascript/README.rst+1 added-2 removed
31 unmodified lines
32---3334.. code-block:: text3536 $ export FLASK_APP=js_example37 $ flask run36 $ flask --app js_example run3738Open http://127.0.0.1:5000 in a browser.3940
8 unmodified lines
modified:examples/tutorial/README.rst+3 added-12 removed
43 unmodified lines
4445Run46---4748::48.. code-block:: text4950 $ export FLASK_APP=flaskr51 $ export FLASK_ENV=development52 $ flask init-db53 $ flask run50 $ flask --app flaskr init-db51 $ flask --app flaskr --env development run5255Or on Windows cmd::5657 > set FLASK_APP=flaskr58 > set FLASK_ENV=development59 > flask init-db60 > flask run6153Open http://127.0.0.1:5000 in a browser.545556Test
12 unmodified lines
modified:src/flask/cli.py+188 added-51 removed
1from __future__ import annotations23import ast4import inspect5import os6import platform
6 unmodified lines
13from threading import Lock14from threading import Thread1516import click17from click.core import ParameterSource18from werkzeug.serving import is_running_from_reloader19from werkzeug.utils import import_string2021from .globals import current_app22from .helpers import get_debug_flag23from .helpers import get_env24from .helpers import get_load_dotenv2526if t.TYPE_CHECKING:27 from .app import Flask282930class NoAppException(click.UsageError):31 """Raised if an application cannot be found or loaded."""3233
17 unmodified lines
51 return matches[0]52 elif len(matches) > 1:53 raise NoAppException(54 "Detected multiple Flask applications in module"49 f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"50 f" to specify the correct one."55 f" '{module.__name__}'. Use '{module.__name__}:name'"56 " to specify the correct one."57 )5859 # Search for app factory functions.60 for attr_name in ("create_app", "make_app"):
9 unmodified lines
70 if not _called_with_wrong_args(app_factory):71 raise7273 raise NoAppException(68 f"Detected factory {attr_name!r} in module {module.__name__!r},"74 f"Detected factory '{attr_name}' in module '{module.__name__}',"75 " but could not call it without arguments. Use"70 f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""76 f" '{module.__name__}:{attr_name}(args)'"77 " to specify arguments."78 ) from e7980 raise NoAppException(81 "Failed to find Flask application or factory in module"76 f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"82 f" '{module.__name__}'. Use '{module.__name__}:name'"83 " to specify one."84 )8586
171 unmodified lines
258259260version_option = click.Option(261 ["--version"],256 help="Show the flask version",262 help="Show the Flask version.",263 expose_value=False,264 callback=get_version,265 is_flag=True,266 is_eager=True,
76 unmodified lines
343 :class:`FlaskGroup` but you can also manually create it and pass it344 onwards as click object.345 """346341 def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):347 def __init__(348 self,349 app_import_path: str | None = None,350 create_app: t.Callable[..., Flask] | None = None,351 set_debug_flag: bool = True,352 ) -> None:353 #: Optionally the import path for the Flask application.343 self.app_import_path = app_import_path or os.environ.get("FLASK_APP")354 self.app_import_path = app_import_path355 #: Optionally a function that is passed the script info to create356 #: the instance of the application.357 self.create_app = create_app358 #: A dictionary with arbitrary data that can be associated with359 #: this script info.349 self.data = {}360 self.data: t.Dict[t.Any, t.Any] = {}361 self.set_debug_flag = set_debug_flag351 self._loaded_app = None362 self._loaded_app: Flask | None = None363353 def load_app(self):364 def load_app(self) -> Flask:365 """Loads the Flask app (if not yet loaded) and returns it. Calling366 this multiple times will just result in the already loaded app to367 be returned.368 """
20 unmodified lines
389 break390391 if not app:392 raise NoAppException(382 "Could not locate a Flask application. You did not provide "383 'the "FLASK_APP" environment variable, and a "wsgi.py" or '384 '"app.py" module was not found in the current directory.'393 "Could not locate a Flask application. Use the"394 " 'flask --app' option, 'FLASK_APP' environment"395 " variable, or a 'wsgi.py' or 'app.py' file in the"396 " current directory."397 )398399 if self.set_debug_flag:400 # Update the app's debug flag through the descriptor so that
52 unmodified lines
453 kwargs.setdefault("cls", AppGroup)454 return click.Group.group(self, *args, **kwargs)455456457def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:458 if value is None:459 return None460461 info = ctx.ensure_object(ScriptInfo)462 info.app_import_path = value463 return value464465466# This option is eager so the app will be available if --help is given.467# --help is also eager, so --app must be before it in the param list.468# no_args_is_help bypasses eager processing, so this option must be469# processed manually in that case to ensure FLASK_APP gets picked up.470_app_option = click.Option(471 ["-A", "--app"],472 metavar="IMPORT",473 help=(474 "The Flask application or factory function to load, in the form 'module:name'."475 " Module can be a dotted import or file path. Name is not required if it is"476 " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to"477 " pass arguments."478 ),479 is_eager=True,480 expose_value=False,481 callback=_set_app,482)483484485def _set_env(ctx: click.Context, param: click.Option, value: str | None) -> str | None:486 if value is None:487 return None488489 # Set with env var instead of ScriptInfo.load so that it can be490 # accessed early during a factory function.491 os.environ["FLASK_ENV"] = value492 return value493494495_env_option = click.Option(496 ["-E", "--env"],497 metavar="NAME",498 help=(499 "The execution environment name to set in 'app.env'. Defaults to"500 " 'production'. 'development' will enable 'app.debug' and start the"501 " debugger and reloader when running the server."502 ),503 expose_value=False,504 callback=_set_env,505)506507508def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:509 # If the flag isn't provided, it will default to False. Don't use510 # that, let debug be set by env in that case.511 source = ctx.get_parameter_source(param.name) # type: ignore[arg-type]512513 if source is not None and source in (514 ParameterSource.DEFAULT,515 ParameterSource.DEFAULT_MAP,516 ):517 return None518519 # Set with env var instead of ScriptInfo.load so that it can be520 # accessed early during a factory function.521 os.environ["FLASK_DEBUG"] = "1" if value else "0"522 return value523524525_debug_option = click.Option(526 ["--debug/--no-debug"],527 help="Set 'app.debug' separately from '--env'.",528 expose_value=False,529 callback=_set_debug,530)531532533def _env_file_callback(534 ctx: click.Context, param: click.Option, value: str | None535) -> str | None:536 if value is None:537 return None538539 import importlib540541 try:542 importlib.import_module("dotenv")543 except ImportError:544 raise click.BadParameter(545 "python-dotenv must be installed to load an env file.",546 ctx=ctx,547 param=param,548 ) from None549550 # Don't check FLASK_SKIP_DOTENV, that only disables automatically551 # loading .env and .flaskenv files.552 load_dotenv(value)553 return value554555556# This option is eager so env vars are loaded as early as possible to be557# used by other options.558_env_file_option = click.Option(559 ["-e", "--env-file"],560 type=click.Path(exists=True, dir_okay=False),561 help="Load environment variables from this file. python-dotenv must be installed.",562 is_eager=True,563 expose_value=False,564 callback=_env_file_callback,565)566567568class FlaskGroup(AppGroup):569 """Special subclass of the :class:`AppGroup` group that supports570 loading more commands from the configured Flask app. Normally a571 developer does not have to interface with this class but there are
10 unmodified lines
582 directory to the directory containing the first file found.583 :param set_debug_flag: Set the app's debug flag based on the active584 environment585586 .. versionchanged:: 2.2587 Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,588 and ``-e/--env-file`` options.589590 .. versionchanged:: 1.0591 If installed, python-dotenv will be used to load environment variables592 from :file:`.env` and :file:`.flaskenv` files.593 """594595 def __init__(596 self,470 add_default_commands=True,471 create_app=None,472 add_version_option=True,473 load_dotenv=True,474 set_debug_flag=True,475 **extra,476 ):597 add_default_commands: bool = True,598 create_app: t.Callable[..., Flask] | None = None,599 add_version_option: bool = True,600 load_dotenv: bool = True,601 set_debug_flag: bool = True,602 **extra: t.Any,603 ) -> None:604 params = list(extra.pop("params", None) or ())605 # Processing is done with option callbacks instead of a group606 # callback. This allows users to make a custom group callback607 # without losing the behavior. --env-file must come first so608 # that it is eagerly evaluated before --app.609 params.extend((_env_file_option, _app_option, _env_option, _debug_option))610611 if add_version_option:612 params.append(version_option)613
72 unmodified lines
686 return sorted(rv)687688 def make_context(689 self,558 info_name: t.Optional[str],559 args: t.List[str],560 parent: t.Optional[click.Context] = None,690 info_name: str | None,691 args: list[str],692 parent: click.Context | None = None,693 **extra: t.Any,694 ) -> click.Context:695 # Attempt to load .env and .flask env files. The --env-file696 # option can cause another file to be loaded.697 if get_load_dotenv(self.load_dotenv):698 load_dotenv()699700 if "obj" not in extra and "obj" not in self.context_settings:
2 unmodified lines
703 )704705 return super().make_context(info_name, args, parent=parent, **extra)706707 def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:708 if not args and self.no_args_is_help:709 # Attempt to load --env-file and --app early in case they710 # were given as env vars. Otherwise no_args_is_help will not711 # see commands from app.cli.712 _env_file_option.handle_parse_result(ctx, {}, [])713 _app_option.handle_parse_result(ctx, {}, [])714715 return super().parse_args(ctx, args)716717718def _path_is_ancestor(path, other):719 """Take ``other`` and remove the length of ``path`` from it. Then join it720 to ``path``. If it is the original value, ``path`` is an ancestor of721 ``other``."""722 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other723724581def load_dotenv(path=None):725def load_dotenv(path: str | os.PathLike | None = None) -> bool:726 """Load "dotenv" files in order of precedence to set environment variables.727728 If an env var is already set it is not overwritten, so earlier files in the729 list are preferred over later files.
4 unmodified lines
734735 :param path: Load the file at this location instead of searching.736 :return: ``True`` if a file was loaded.737594 .. versionchanged:: 1.1.0595 Returns ``False`` when python-dotenv is not installed, or when596 the given path isn't a file.738 .. versionchanged:: 2.0739 The current directory is not changed to the location of the740 loaded file.741742 .. versionchanged:: 2.0743 When loading the env files, set the default encoding to UTF-8.744745 .. versionchanged:: 1.1.0746 Returns ``False`` when python-dotenv is not installed, or when747 the given path isn't a file.748749 .. versionadded:: 1.0750 """751 try:752 import dotenv
7 unmodified lines
760 )761762 return False763616 # if the given path specifies the actual file then return True,617 # else False764 # Always return after attempting to load a given path, don't load765 # the default files.766 if path is not None:767 if os.path.isfile(path):768 return dotenv.load_dotenv(path, encoding="utf-8")769770 return False771624 new_dir = None772 loaded = False773774 for name in (".env", ".flaskenv"):775 path = dotenv.find_dotenv(name, usecwd=True)776777 if not path:778 continue779632 if new_dir is None:633 new_dir = os.path.dirname(path)634780 dotenv.load_dotenv(path, encoding="utf-8")781 loaded = True782637 return new_dir is not None # at least one file was located and loaded783 return loaded # True if at least one file was located and loaded.784785786def show_server_banner(env, debug, app_import_path, eager_loading):787 """Show extra startup messages the first time the server is run,
194 unmodified lines
982983 This server is for development purposes only. It does not provide984 the stability, security, or performance of production WSGI servers.985840 The reloader and debugger are enabled by default if841 FLASK_ENV=development or FLASK_DEBUG=1.986 The reloader and debugger are enabled by default with the987 '--env development' or '--debug' options.988 """989 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)990 debug = get_debug_flag()991992 if reload is None:993 reload = debug
1 unmodified line
995 if debugger is None:996 debugger = debug997998 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)852 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)9991000 from werkzeug.serving import run_simple10011002 run_simple(
113 unmodified lines
1116 name="flask",1117 help="""\1118A general utility script for Flask applications.1119974Provides commands from Flask, extensions, and the application. Loads the975application defined in the FLASK_APP environment variable, or from a wsgi.py976file. Setting the FLASK_ENV environment variable to 'development' will enable977debug mode.978979\b980 {prefix}{cmd} FLASK_APP=hello.py981 {prefix}{cmd} FLASK_ENV=development982 {prefix}flask run983""".format(984 cmd="export" if os.name == "posix" else "set",985 prefix="$ " if os.name == "posix" else "> ",986 ),1120An application to load must be given with the '--app' option,1121'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file1122in the current directory.1123""",1124)112511261127def main() -> None:
5 unmodified lines
modified:src/flask/helpers.py+3 added-3 removed
46 unmodified lines
47 return val.lower() not in ("0", "false", "no")484950def get_load_dotenv(default: bool = True) -> bool:51 """Get whether the user has disabled loading dotenv files by setting52 :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the53 files.51 """Get whether the user has disabled loading default dotenv files by52 setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load53 the files.5455 :param default: What to return if the env var isn't set.56 """57 val = os.environ.get("FLASK_SKIP_DOTENV")
687 unmodified lines
modified:tests/conftest.py+1 added
16 unmodified lines
17 :func:`._reset_os_environ` after each test.18 """19 mp = monkeypatch.MonkeyPatch()20 out = (21 (os.environ, "FLASK_ENV_FILE", monkeypatch.notset),22 (os.environ, "FLASK_APP", monkeypatch.notset),23 (os.environ, "FLASK_ENV", monkeypatch.notset),24 (os.environ, "FLASK_DEBUG", monkeypatch.notset),25 (os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),
173 unmodified lines
modified:CHANGES.rst+6 added
25 unmodified lines
26 subclass sets this to ``False``, the view will not create a new27 instance on every request. :issue:`2520`.28- A ``flask.cli.FlaskGroup`` Click group can be nested as a29 sub-command in a custom CLI. :issue:`3263`30- Add ``--app``, ``--env``, and ``--debug`` options to the ``flask``31 CLI, instead of requiring that they are set through environment32 variables. :issue:`2836`33- Add ``--env-file`` option to the ``flask`` CLI. This allows34 specifying a dotenv file to load in addition to ``.env`` and35 ``.flaskenv``. :issue:`3108`363738Version 2.1.339-------------
1291 unmodified lines