Skip to content
Myr

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

10 files+151 added−71 removed

modified:docs/patterns/packages.rst+3 added-3 removed
63 unmodified lines
6465 export FLASK_APP=yourapplication6667If you are outside of the project directory make sure to provide the exact 68path to your application directory. Similarly you can turn on "debug 69mode" with this environment variable:: 68path to your application directory. Similarly you can turn on the69development features like this::7071 export FLASK_DEBUG=true 71 export FLASK_ENV=development7273In order to install and run the application you need to issue the following 74commands::75
70 unmodified lines
modified:docs/tutorial/packaging.rst+4 added-2 removed
76 unmodified lines
77With that out of the way, you should be able to start up the application.78Do this on Mac or Linux with the following commands in ``flaskr/``::7980 export FLASK_APP=flaskr81 export FLASK_DEBUG=true81 export FLASK_ENV=development82 flask run8384(In case you are on Windows you need to use ``set`` instead of ``export``).85The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.85The :envvar:`FLASK_ENV` flag if set to ``development`` turns on all86development features such as enabling the interactive debugger.8788*Never leave debug mode activated in a production system*, because it will89allow users to execute code on the server!9091You will see a message telling you that server has started along with
17 unmodified lines
modified:docs/cli.rst+14 added-1 removed
114 unmodified lines
115 >>>116117Use :meth:`~Flask.shell_context_processor` to add other automatic imports.118119Environments120------------121122.. versionadded:: 1.0123124The 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 is128for instance automatically enabled.129130Debug Mode131----------132133Set the :envvar:`FLASK_DEBUG` environment variable to override the134application's :attr:`~Flask.debug` flag. The value ``1`` enables it, ``0``135disables it. Forcing the debug flag on also enables the debugger and reloader126when running the development server. ::136when running the development server.137138::139140 $ 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-919
259 unmodified lines
modified:docs/config.rst+30 added-13 removed
25 unmodified lines
26The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and27can be modified just like any dictionary::2829 app = Flask(__name__)30 app.config['DEBUG'] = True30 app.config['TESTING'] = True3132Certain configuration values are also forwarded to the33:attr:`~flask.Flask` object so you can read and write them from there::3435 app.debug = True35 app.testing = True3637To update multiple keys at once you can use the :meth:`dict.update`38method::3940 app.config.update(41 DEBUG=True,41 TESTING=True,42 SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'43 )4445.. admonition:: Debug Mode with the ``flask`` Script45Environment and Debug Features46------------------------------4747 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::48Some values are special in that they can show unexpected behavior when49changed late. In particular that applies to the Flask environment and50debug mode.5151 $ export FLASK_DEBUG=152 $ flask run52If you use the :command:`flask` script to start a local development server53for instance you should tell Flask that you want to work in the54development environment. For safety reasons we default the flask55environment to production mode instead of development. This is done56because development mode can turn on potentially unsafe features such as57the debugger by default.5854 (On Windows you need to use ``set`` instead of ``export``).59To control the environment and such fundamental features Flask provides60the two environment variables :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`.61In versions of Flask older than 1.0 the :envvar:`FLASK_ENV` environment62variable did not exist.6356 ``app.debug`` and ``app.config['DEBUG']`` are not compatible with57   the :command:`flask` script. They only worked when using ``Flask.run()``58 method.64The most common way to switch Flask to development mode is to tell it to65work on the ``development`` environment::6667$ export FLASK_ENV=development68$ flask run6970(On Windows you need to use ``set`` instead of ``export``).7172While you can attempt to flip the environment and debug flag separately in73the Flask config from the config file this is strongly discouraged as74those flags are often loaded early and changing them late might not apply75to all systems and extensions.7677Builtin Configuration Values78----------------------------7980The following configuration values are used internally by Flask:
528 unmodified lines
modified:docs/quickstart.rst+6 added-3 removed
128 unmodified lines
129That is not very nice and Flask can do better. If you enable debug130support the server will reload itself on code changes, and it will also131provide you with a helpful debugger if things go wrong.132133To enable debug mode you can export the ``FLASK_DEBUG`` environment variable133To enable all development features (and to disable the debug mode) you can134export the ``FLASK_ENV`` environment variable and set it to135``development``136before running the server::137136 $ export FLASK_DEBUG=1138 $ export FLASK_ENV=development139 $ flask run140139(On Windows you need to use ``set`` instead of ``export``).141(On Windows you need to use ``set`` instead of ``export`` and on Flask142versions older than 1.0 you need to export ``FLASK_DEBUG=1`` instead).143144This does the following things:1451461. it activates the debugger
703 unmodified lines
modified:docs/server.rst+12 added-4 removed
10 unmodified lines
1112Command Line13------------1415The :command:`flask` command line script (:ref:`cli`) is strongly recommended for16development because it provides a superior reload experience due to how it17loads the application. The basic usage is like this::15The :command:`flask` command line script (:ref:`cli`) is strongly16recommended for development because it provides a superior reload17experience due to how it loads the application. The basic usage is like18this::1920 $ export FLASK_APP=my_application20 $ export FLASK_DEBUG=121 $ export FLASK_ENV=development22 $ flask run2324This will enable the debugger, the reloader and then start the server on25*http://localhost:5000/*.
3 unmodified lines
29disabled::3031 $ flask run --no-reload3233.. note::3435 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``.3940In Code41-------4243The alternative way to start the application is through the
17 unmodified lines
modified:flask/app.py+38 added-29 removed
25 unmodified lines
26from .config import Config, ConfigAttribute27from .ctx import AppContext, RequestContext, _AppCtxGlobals28from .globals import _request_ctx_stack, g, request, session29from .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_for32from .logging import create_logger33from .sessions import SecureCookieSessionInterface34from .signals import appcontext_tearing_down, got_request_exception, \
160 unmodified lines
195 #:196 #: .. versionadded:: 0.11197 config_class = Config198199 #: 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')207199 #: 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 lines
268 )269270 #: 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 lines
638 """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)646647 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 calculate
134 unmodified lines
784 for processor in self.shell_context_processors:785 rv.update(processor())786 return rv787793 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')794798 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)799801 :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_debug813803 .. 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_reload817809 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.821822 Do not use ``run()`` in a production setting. It is not intended to823 meet security and performance requirements for a production server.
55 unmodified lines
879 from flask.cli import load_dotenv880 load_dotenv()881882 if debug is not None:875 self._reconfigure_for_run_debug(bool(debug))883 self.debug = bool(debug)884885 _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, None889890 if server_name:891 sn_host, _, sn_port = server_name.partition(':')
170 unmodified lines
1062 """1063 return iter(self._blueprint_order)10641065 @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 lines
modified:flask/cli.py+18 added-11 removed
23 unmodified lines
2425from . import __version__26from ._compat import getargspec, iteritems, reraise27from .globals import current_app28from .helpers import get_debug_flag28from .helpers import get_debug_flag, get_env2930try:31 import dotenv32except ImportError:
307 unmodified lines
340 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)346347 if app:348 break349
5 unmodified lines
355 )356357 debug = get_debug_flag()358359 # 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 = debug363364 self._loaded_app = app365 return app366
65 unmodified lines
432 If installed, python-dotenv will be used to load environment variables433 from :file:`.env` and :file:`.flaskenv` files.434 """435435 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 ())439440 if add_version_option:441 params.append(version_option)
166 unmodified lines
608 Flask is enabled and disabled otherwise.609 """610 from werkzeug.serving import run_simple611612 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)618619 debug = get_debug_flag()620 if reload is None:621 reload = bool(debug)622 if debugger is None:
11 unmodified lines
634 # 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'))641642 run_simple(host, port, app, use_reloader=reload,
12 unmodified lines
655 """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 lines
modified:flask/helpers.py+12 added-2 removed
44 unmodified lines
45_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]46 if sep not in (None, '/'))474849def get_debug_flag(default=None):49def get_env():50 val = os.environ.get('FLASK_ENV')51 if not val:52 val = 'production'53 return val545556def 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')646566def _endpoint_from_view_func(view_func):
963 unmodified lines
modified:tests/test_helpers.py+14 added-3 removed
19 unmodified lines
20 parse_options_header2122import flask23from flask._compat import StringIO, text_type24from flask.helpers import get_debug_flag24from flask.helpers import get_debug_flag, get_env252627def has_encoding(name):28 try:
856 unmodified lines
885886class TestHelpers(object):887888 @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 lines
897 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_flag902903 @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_env913914 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