Add Support for FLASK_ENV (#2570)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This introduces environments to Flask
authored by Armin Ronacher · committed by GitHub · parent 60eecb5 · Browse files · 10 files·+151 added−71 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+151 added−71 removed
- tests:+14 added−3 removed
- other:+137 added−68 removed
Provenance
- Commit
2433522- Tree
b9e0277- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
GitHub <noreply@github.com>- Parent
60eecb5
10 files changed+151 added−71 removed
modified:docs/patterns/packages.rst+3 added-3 removed
63 unmodified lines64 65 export FLASK_APP=yourapplication66 67 If you are outside of the project directory make sure to provide the exact 68-path to your application directory. Similarly you can turn on "debug 69-mode" with this environment variable:: 68+path to your application directory. Similarly you can turn on the69+development features like this::70 71- export FLASK_DEBUG=true 71+ export FLASK_ENV=development72 73 In order to install and run the application you need to issue the following 74 commands::75 70 unmodified linesmodified:docs/tutorial/packaging.rst+4 added-2 removed
76 unmodified lines77 With that out of the way, you should be able to start up the application.78 Do this on Mac or Linux with the following commands in ``flaskr/``::79 80 export FLASK_APP=flaskr81- export FLASK_DEBUG=true81+ export FLASK_ENV=development82 flask run83 84 (In case you are on Windows you need to use ``set`` instead of ``export``).85-The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.85+The :envvar:`FLASK_ENV` flag if set to ``development`` turns on all86+development features such as enabling the interactive debugger.87+88 *Never leave debug mode activated in a production system*, because it will89 allow users to execute code on the server!90 91 You will see a message telling you that server has started along with17 unmodified linesmodified:docs/cli.rst+14 added-1 removed
114 unmodified lines115 >>>116 117 Use :meth:`~Flask.shell_context_processor` to add other automatic imports.118 119+Environments120+------------121 122+.. versionadded:: 1.0123+124+The environment in which the Flask app should run is set by the125+:envvar:`FLASK_ENV` environment variable. If not set it defaults to126+``production``. The other default environment which is known is127+``development``. If the env is set to ``development`` the debug mode is128+for instance automatically enabled.129+130 Debug Mode131 ----------132 133 Set the :envvar:`FLASK_DEBUG` environment variable to override the134 application's :attr:`~Flask.debug` flag. The value ``1`` enables it, ``0``135 disables it. Forcing the debug flag on also enables the debugger and reloader126-when running the development server. ::136+when running the development server.137 138+::139+140 $ FLASK_DEBUG=1 flask run141 * Serving Flask app "hello"142 * Forcing debug mode on143+ * Env production144 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)145 * Restarting with inotify reloader146 * Debugger is active!147 * Debugger PIN: 223-456-919259 unmodified linesmodified:docs/config.rst+30 added-13 removed
25 unmodified lines26 The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and27 can be modified just like any dictionary::28 29 app = Flask(__name__)30- app.config['DEBUG'] = True30+ app.config['TESTING'] = True31 32 Certain configuration values are also forwarded to the33 :attr:`~flask.Flask` object so you can read and write them from there::34 35- app.debug = True35+ app.testing = True36 37 To update multiple keys at once you can use the :meth:`dict.update`38 method::39 40 app.config.update(41- DEBUG=True,41+ TESTING=True,42 SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'43 )44 45-.. admonition:: Debug Mode with the ``flask`` Script45+Environment and Debug Features46+------------------------------47 47- If you use the :command:`flask` script to start a local development48- server, to enable the debug mode, you need to export the ``FLASK_DEBUG``49- environment variable before running the server::48+Some values are special in that they can show unexpected behavior when49+changed late. In particular that applies to the Flask environment and50+debug mode.51 51- $ export FLASK_DEBUG=152- $ flask run52+If you use the :command:`flask` script to start a local development server53+for instance you should tell Flask that you want to work in the54+development environment. For safety reasons we default the flask55+environment to production mode instead of development. This is done56+because development mode can turn on potentially unsafe features such as57+the debugger by default.58 54- (On Windows you need to use ``set`` instead of ``export``).59+To control the environment and such fundamental features Flask provides60+the two environment variables :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`.61+In versions of Flask older than 1.0 the :envvar:`FLASK_ENV` environment62+variable did not exist.63 56- ``app.debug`` and ``app.config['DEBUG']`` are not compatible with57- the :command:`flask` script. They only worked when using ``Flask.run()``58- method.64+The most common way to switch Flask to development mode is to tell it to65+work on the ``development`` environment::66 67+$ export FLASK_ENV=development68+$ flask run69+70+(On Windows you need to use ``set`` instead of ``export``).71+72+While you can attempt to flip the environment and debug flag separately in73+the Flask config from the config file this is strongly discouraged as74+those flags are often loaded early and changing them late might not apply75+to all systems and extensions.76+77 Builtin Configuration Values78 ----------------------------79 80 The following configuration values are used internally by Flask:528 unmodified linesmodified:docs/quickstart.rst+6 added-3 removed
128 unmodified lines129 That is not very nice and Flask can do better. If you enable debug130 support the server will reload itself on code changes, and it will also131 provide you with a helpful debugger if things go wrong.132 133-To enable debug mode you can export the ``FLASK_DEBUG`` environment variable133+To enable all development features (and to disable the debug mode) you can134+export the ``FLASK_ENV`` environment variable and set it to135+``development``136 before running the server::137 136- $ export FLASK_DEBUG=1138+ $ export FLASK_ENV=development139 $ flask run140 139-(On Windows you need to use ``set`` instead of ``export``).141+(On Windows you need to use ``set`` instead of ``export`` and on Flask142+versions older than 1.0 you need to export ``FLASK_DEBUG=1`` instead).143 144 This does the following things:145 146 1. it activates the debugger703 unmodified linesmodified:docs/server.rst+12 added-4 removed
10 unmodified lines11 12 Command Line13 ------------14 15-The :command:`flask` command line script (:ref:`cli`) is strongly recommended for16-development because it provides a superior reload experience due to how it17-loads the application. The basic usage is like this::15+The :command:`flask` command line script (:ref:`cli`) is strongly16+recommended for development because it provides a superior reload17+experience due to how it loads the application. The basic usage is like18+this::19 20 $ export FLASK_APP=my_application20- $ export FLASK_DEBUG=121+ $ export FLASK_ENV=development22 $ flask run23 24 This will enable the debugger, the reloader and then start the server on25 *http://localhost:5000/*.3 unmodified lines29 disabled::30 31 $ flask run --no-reload32 33+.. note::34+35+ On older Flask version (before 1.0) the :envvar:`FLASK_ENV`36+ environment variable is not supported and you need to enable the37+ debug mode separately by setting the :envvar:`FLASK_DEBUG` environment38+ variable to ``1``.39+40 In Code41 -------42 43 The alternative way to start the application is through the17 unmodified linesmodified:flask/app.py+38 added-29 removed
25 unmodified lines26 from .config import Config, ConfigAttribute27 from .ctx import AppContext, RequestContext, _AppCtxGlobals28 from .globals import _request_ctx_stack, g, request, session29 from .helpers import _PackageBoundObject, \30- _endpoint_from_view_func, find_package, get_debug_flag, \30+ _endpoint_from_view_func, find_package, get_env, get_debug_flag, \31 get_flashed_messages, locked_cached_property, url_for32 from .logging import create_logger33 from .sessions import SecureCookieSessionInterface34 from .signals import appcontext_tearing_down, got_request_exception, \160 unmodified lines195 #:196 #: .. versionadded:: 0.11197 config_class = Config198 199- #: The debug flag. Set this to ``True`` to enable debugging of the200- #: application. In debug mode the debugger will kick in when an unhandled201- #: exception occurs and the integrated server will automatically reload202- #: the application if changes in the code are detected.203- #:204- #: This attribute can also be configured from the config with the ``DEBUG``205- #: configuration key. Defaults to ``False``.206- debug = ConfigAttribute('DEBUG')207-199 #: The testing flag. Set this to ``True`` to enable the test mode of200 #: Flask extensions (and in the future probably also Flask itself).201 #: For example this might activate test helpers that have an202 #: additional runtime cost which should not be enabled by default.65 unmodified lines268 )269 270 #: Default configuration parameters.271 default_config = ImmutableDict({281- 'DEBUG': get_debug_flag(default=False),272+ 'ENV': None,273+ 'DEBUG': None,274 'TESTING': False,275 'PROPAGATE_EXCEPTIONS': None,276 'PRESERVE_CONTEXT_ON_EXCEPTION': None,277 'SECRET_KEY': None,360 unmodified lines638 """639 root_path = self.root_path640 if instance_relative:641 root_path = self.instance_path650- return self.config_class(root_path, self.default_config)642+ defaults = dict(self.default_config)643+ defaults['ENV'] = get_env()644+ defaults['DEBUG'] = get_debug_flag()645+ return self.config_class(root_path, defaults)646 647 def auto_find_instance_path(self):648 """Tries to locate the instance path if it was not provided to the649 constructor of the application class. It will basically calculate134 unmodified lines784 for processor in self.shell_context_processors:785 rv.update(processor())786 return rv787 793- def _reconfigure_for_run_debug(self, debug):794- """The ``run`` commands will set the application's debug flag. Some795- application configuration may already be calculated based on the796- previous debug value. This method will recalculate affected values.788+ #: The environment value. This is typically set from outside the789+ #: process by setting the `FLASK_ENV` environment variable and can be790+ #: used to quickly switch between different environments like791+ #: `production` and `development`. If not set this defaults to792+ #: `production`.793+ env = ConfigAttribute('ENV')794 798- Called by the :func:`flask.cli.run` command or :meth:`Flask.run`799- method if the debug flag is set explicitly in the call.795+ def _get_debug(self):796+ return self.config['DEBUG']797+ def _set_debug(self, value):798+ self._set_debug_value(value)799 801- :param debug: the new value of the debug flag800+ #: The debug flag. If this is ``True`` it enables debugging of the801+ #: application. In debug mode the debugger will kick in when an802+ #: unhandled exception occurs and the integrated server will803+ #: automatically reload the application if changes in the code are804+ #: detected.805+ #:806+ #: This value should only be configured by the :envvar:`FLASK_DEBUG`807+ #: environment variable. Changing it by other means will not yield808+ #: consistent results. The default value depends on the Flask809+ #: environment and will be true for the development environment and false810+ #: otherwise.811+ debug = property(_get_debug, _set_debug)812+ del _get_debug, _set_debug813 803- .. versionadded:: 1.0804- Reconfigures ``app.jinja_env.auto_reload``.805- """806- self.debug = debug814+ def _set_debug_value(self, value):815+ self.config['DEBUG'] = value816 self.jinja_env.auto_reload = self.templates_auto_reload817 809- def run(810- self, host=None, port=None, debug=None, load_dotenv=True, **options811- ):818+ def run(self, host=None, port=None, debug=None,819+ load_dotenv=True, **options):820 """Runs the application on a local development server.821 822 Do not use ``run()`` in a production setting. It is not intended to823 meet security and performance requirements for a production server.55 unmodified lines879 from flask.cli import load_dotenv880 load_dotenv()881 882 if debug is not None:875- self._reconfigure_for_run_debug(bool(debug))883+ self.debug = bool(debug)884 885 _host = '127.0.0.1'886 _port = 5000879- server_name = self.config.get("SERVER_NAME")887+ server_name = self.config.get('SERVER_NAME')888 sn_host, sn_port = None, None889 890 if server_name:891 sn_host, _, sn_port = server_name.partition(':')170 unmodified lines1062 """1063 return iter(self._blueprint_order)1064 1065 @setupmethod1058- def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):1066+ def add_url_rule(self, rule, endpoint=None, view_func=None,1067+ provide_automatic_options=None, **options):1068 """Connects a URL rule. Works exactly like the :meth:`route`1069 decorator. If a view_func is provided it will be registered with the1070 endpoint.1071 1121 unmodified linesmodified:flask/cli.py+18 added-11 removed
23 unmodified lines24 25 from . import __version__26 from ._compat import getargspec, iteritems, reraise27 from .globals import current_app28-from .helpers import get_debug_flag28+from .helpers import get_debug_flag, get_env29 30 try:31 import dotenv32 except ImportError:307 unmodified lines340 app = locate_app(self, import_name, name)341 else:342 for path in ('wsgi.py', 'app.py'):343 import_name = prepare_import(path)344- app = locate_app(345- self, import_name, None, raise_if_not_found=False346- )344+ app = locate_app(self, import_name, None,345+ raise_if_not_found=False)346 347 if app:348 break349 5 unmodified lines355 )356 357 debug = get_debug_flag()358 359+ # Update the app's debug flag through the descriptor so that other360+ # values repopulate as well.361 if debug is not None:361- app._reconfigure_for_run_debug(debug)362+ app.debug = debug363 364 self._loaded_app = app365 return app366 65 unmodified lines432 If installed, python-dotenv will be used to load environment variables433 from :file:`.env` and :file:`.flaskenv` files.434 """435 435- def __init__(436- self, add_default_commands=True, create_app=None,437- add_version_option=True, load_dotenv=True, **extra436+ def __init__(self, add_default_commands=True, create_app=None,437+ add_version_option=True, load_dotenv=True, **extra):438- ):438 params = list(extra.pop('params', None) or ())439 440 if add_version_option:441 params.append(version_option)166 unmodified lines608 Flask is enabled and disabled otherwise.609 """610 from werkzeug.serving import run_simple611 612+ if get_env() == 'production':613+ click.secho('Warning: Detected a production environment. Do not '614+ 'use `flask run` for production use.',615+ fg='red')616+ click.secho('Use a production ready WSGI server instead',617+ dim=True)618+619 debug = get_debug_flag()620 if reload is None:621 reload = bool(debug)622 if debugger is None:11 unmodified lines634 # import path because the app was loaded through a callback then635 # we won't print anything.636 if info.app_import_path is not None:637 print(' * Serving Flask app "%s"' % info.app_import_path)638+ print(' * Env %s' % get_env())639 if debug is not None:640 print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))641 642 run_simple(host, port, app, use_reloader=reload,12 unmodified lines655 """656 import code657 from flask.globals import _app_ctx_stack658 app = _app_ctx_stack.top.app652- banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % (659+ banner = 'Python %s on %s\nApp: %s [%s]\nInstance: %s' % (660 sys.version,661 sys.platform,662 app.import_name,656- app.debug and ' [debug]' or '',663+ app.env,664 app.instance_path,665 )666 ctx = {}667 99 unmodified linesmodified:flask/helpers.py+12 added-2 removed
44 unmodified lines45 _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]46 if sep not in (None, '/'))47 48 49-def get_debug_flag(default=None):49+def get_env():50+ val = os.environ.get('FLASK_ENV')51+ if not val:52+ val = 'production'53+ return val54+55+56+def get_debug_flag():57 val = os.environ.get('FLASK_DEBUG')58 if not val:52- return default59+ env = get_env()60+ if env == 'development':61+ return True62+ return False63 return val.lower() not in ('0', 'false', 'no')64 65 66 def _endpoint_from_view_func(view_func):963 unmodified linesmodified:tests/test_helpers.py+14 added-3 removed
19 unmodified lines20 parse_options_header21 22 import flask23 from flask._compat import StringIO, text_type24-from flask.helpers import get_debug_flag24+from flask.helpers import get_debug_flag, get_env25 26 27 def has_encoding(name):28 try:856 unmodified lines885 886 class TestHelpers(object):887 888 @pytest.mark.parametrize('debug, expected_flag, expected_default_flag', [889- ('', None, True),889+ ('', False, False),890 ('0', False, False),891 ('False', False, False),892 ('No', False, False),893 ('True', True, True)3 unmodified lines897 if expected_flag is None:898 assert get_debug_flag() is None899 else:900 assert get_debug_flag() == expected_flag901- assert get_debug_flag(default=True) == expected_default_flag901+ assert get_debug_flag() == expected_default_flag902 903+ @pytest.mark.parametrize('env, ref_env, debug', [904+ ('', 'production', False),905+ ('production', 'production', False),906+ ('development', 'development', True),907+ ('other', 'other', False),908+ ])909+ def test_get_env(self, monkeypatch, env, ref_env, debug):910+ monkeypatch.setenv('FLASK_ENV', env)911+ assert get_debug_flag() == debug912+ assert get_env() == ref_env913+914 def test_make_response(self):915 app = flask.Flask(__name__)916 with app.test_request_context():917 rv = flask.helpers.make_response()7 unmodified lines