Merge pull request #2416 from davidism/dotenv
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add .env support
authored by David Lord · committed by GitHub · parents 8e2ef5b, 491d331 · Browse files · 13 files·+235 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+235 added−42 removed
- tests:+71 added−8 removed
- other:+164 added−34 removed
Provenance
- Commit
851eaa4- Tree
3ea19d1- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
8e2ef5b- Parent 2
491d331
13 files changed+235 added−42 removed
modified:docs/api.rst+2 added
812 unmodified lines813 814 .. autoclass:: ScriptInfo815 :members:816 817+.. autofunction:: load_dotenv818+819 .. autofunction:: with_appcontext820 821 .. autofunction:: pass_script_info822 6 unmodified linesmodified:docs/cli.rst+31 added-3 removed
95 unmodified lines96 Custom Commands97 ---------------98 99 If you want to add more commands to the shell script you can do this100-easily. Flask uses `click`_ for the command interface which makes101-creating custom commands very easy. For instance if you want a shell102-command to initialize the database you can do this::100+easily. For instance if you want a shell command to initialize the database you101+can do this::102 103 import click104 from flask import Flask105 26 unmodified lines132 @app.cli.command(with_appcontext=False)133 def example():134 pass135 136+137+.. _dotenv:138+139+Loading Environment Variables From ``.env`` Files140+-------------------------------------------------141+142+If `python-dotenv`_ is installed, running the :command:`flask` command will set143+environment variables defined in the files :file:`.env` and :file:`.flaskenv`.144+This can be used to avoid having to set ``FLASK_APP`` manually every time you145+open a new terminal, and to set configuration using environment variables146+similar to how some deployment services work.147+148+Variables set on the command line are used over those set in :file:`.env`,149+which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be150+used for public variables, such as ``FLASK_APP``, while :file:`.env` should not151+be committed to your repository so that it can set private variables.152+153+Directories are scanned upwards from the directory you call :command:`flask`154+from to locate the files. The current working directory will be set to the155+location of the file, with the assumption that that is the top level project156+directory.157+158+The files are only loaded by the :command:`flask` command or calling159+:meth:`~flask.Flask.run`. If you would like to load these files when running in160+production, you should call :func:`~flask.cli.load_dotenv` manually.161+162+.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme163+164+165 Factory Functions166 -----------------167 168 In case you are using factory functions to create your application (see167 unmodified linesmodified:docs/installation.rst+3 added
39 unmodified lines40 * `Blinker`_ provides support for :ref:`signals`.41 * `SimpleJSON`_ is a fast JSON implementation that is compatible with42 Python's ``json`` module. It is preferred for JSON operations if it is43 installed.44+* `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask``45+ commands.46 47 .. _Blinker: https://pythonhosted.org/blinker/48 .. _SimpleJSON: https://simplejson.readthedocs.io/49+.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme50 51 Virtual environments52 --------------------53 125 unmodified linesmodified:flask/app.py+27 added-15 removed
818 unmodified lines819 """820 self.debug = debug821 self.jinja_env.auto_reload = self.templates_auto_reload822 823- def run(self, host=None, port=None, debug=None, **options):823+ def run(824+ self, host=None, port=None, debug=None, load_dotenv=True, **options825+ ):826 """Runs the application on a local development server.827 828 Do not use ``run()`` in a production setting. It is not intended to829 meet security and performance requirements for a production server.20 unmodified lines850 Setting ``use_debugger`` to ``True`` without being in debug mode851 won't catch any exceptions because there won't be any to852 catch.853 854+ :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to855+ have the server available externally as well. Defaults to856+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable857+ if present.858+ :param port: the port of the webserver. Defaults to ``5000`` or the859+ port defined in the ``SERVER_NAME`` config variable if present.860+ :param debug: if given, enable or disable debug mode. See861+ :attr:`debug`.862+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`863+ files to set environment variables. Will also change the working864+ directory to the directory containing the first file found.865+ :param options: the options to be forwarded to the underlying Werkzeug866+ server. See :func:`werkzeug.serving.run_simple` for more867+ information.868+869+ .. versionchanged:: 1.0870+ If installed, python-dotenv will be used to load environment871+ variables from :file:`.env` and :file:`.flaskenv` files.872+873 .. versionchanged:: 0.10874 The default port is now picked from the ``SERVER_NAME`` variable.875 855- :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to856- have the server available externally as well. Defaults to857- ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config858- variable if present.859- :param port: the port of the webserver. Defaults to ``5000`` or the860- port defined in the ``SERVER_NAME`` config variable if861- present.862- :param debug: if given, enable or disable debug mode.863- See :attr:`debug`.864- :param options: the options to be forwarded to the underlying865- Werkzeug server. See866- :func:`werkzeug.serving.run_simple` for more867- information.876 """877 # Change this into a no-op if the server is invoked from the878 # command line. Have a look at cli.py for more information.871- if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':879+ if os.environ.get('FLASK_RUN_FROM_CLI') == 'true':880 from .debughelpers import explain_ignored_app_run881 explain_ignored_app_run()882 return883 884+ if load_dotenv:885+ from flask.cli import load_dotenv886+ load_dotenv()887+888 if debug is not None:889 self._reconfigure_for_run_debug(bool(debug))890 891 _host = '127.0.0.1'1306 unmodified linesmodified:flask/cli.py+86 added-15 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+from __future__ import print_function12 13 import ast14 import inspect15 import os6 unmodified lines22 23 import click24 25 from . import __version__25-from ._compat import iteritems, reraise26+from ._compat import getargspec, iteritems, reraise27 from .globals import current_app28 from .helpers import get_debug_flag28-from ._compat import getargspec29 30+try:31+ import dotenv32+except ImportError:33+ dotenv = None34 35+36 class NoAppException(click.UsageError):37 """Raised if an application cannot be found or loaded."""38 39 358 unmodified lines398 399 For information as of why this is useful see :ref:`custom-scripts`.400 401 :param add_default_commands: if this is True then the default run and397- shell commands wil be added.402+ shell commands wil be added.403 :param add_version_option: adds the ``--version`` option.399- :param create_app: an optional callback that is passed the script info400- and returns the loaded app.404+ :param create_app: an optional callback that is passed the script info and405+ returns the loaded app.406+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`407+ files to set environment variables. Will also change the working408+ directory to the directory containing the first file found.409+410+ .. versionchanged:: 1.0411+ If installed, python-dotenv will be used to load environment variables412+ from :file:`.env` and :file:`.flaskenv` files.413 """414 415+ def __init__(403- def __init__(self, add_default_commands=True, create_app=None,404- add_version_option=True, **extra):416+ self, add_default_commands=True, create_app=None,417+ add_version_option=True, load_dotenv=True, **extra418+ ):419 params = list(extra.pop('params', None) or ())420 421 if add_version_option:422 params.append(version_option)423 424 AppGroup.__init__(self, params=params, **extra)425 self.create_app = create_app426+ self.load_dotenv = load_dotenv427 428 if add_default_commands:429 self.add_command(run_command)430 self.add_command(shell_command)55 unmodified lines486 traceback.print_exc()487 return sorted(rv)488 489 def main(self, *args, **kwargs):490+ # Set a global flag that indicates that we were invoked from the491+ # command line interface. This is detected by Flask.run to make the492+ # call into a no-op. This is necessary to avoid ugly errors when the493+ # script that is loaded here also attempts to start a server.494+ os.environ['FLASK_RUN_FROM_CLI'] = 'true'495+496+ if self.load_dotenv:497+ load_dotenv()498+499 obj = kwargs.get('obj')500+501 if obj is None:502 obj = ScriptInfo(create_app=self.create_app)503+504 kwargs['obj'] = obj505 kwargs.setdefault('auto_envvar_prefix', 'FLASK')480- return AppGroup.main(self, *args, **kwargs)506+ return super(FlaskGroup, self).main(*args, **kwargs)507 508 509+def _path_is_ancestor(path, other):510+ """Take ``other`` and remove the length of ``path`` from it. Then join it511+ to ``path``. If it is the original value, ``path`` is an ancestor of512+ ``other``."""513+ return os.path.join(path, other[len(path):].lstrip(os.sep)) == other514+515+516+def load_dotenv(path=None):517+ """Load "dotenv" files in order of precedence to set environment variables.518+519+ If an env var is already set it is not overwritten, so earlier files in the520+ list are preferred over later files.521+522+ Changes the current working directory to the location of the first file523+ found, with the assumption that it is in the top level project directory524+ and will be where the Python path should import local packages from.525+526+ This is a no-op if `python-dotenv`_ is not installed.527+528+ .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme529+530+ :param path: Load the file at this location instead of searching.531+ :return: ``True`` if a file was loaded.532+533+ .. versionadded:: 1.0534+ """535+536+ if dotenv is None:537+ return538+539+ if path is not None:540+ return dotenv.load_dotenv(path)541+542+ new_dir = None543+544+ for name in ('.env', '.flaskenv'):545+ path = dotenv.find_dotenv(name, usecwd=True)546+547+ if not path:548+ continue549+550+ if new_dir is None:551+ new_dir = os.path.dirname(path)552+553+ dotenv.load_dotenv(path)554+555+ if new_dir and os.getcwd() != new_dir:556+ os.chdir(new_dir)557+558+ return new_dir is not None # at least one file was located and loaded559+560+561 @click.command('run', short_help='Runs a development server.')562 @click.option('--host', '-h', default='127.0.0.1',563 help='The interface to bind to.')564 @click.option('--port', '-p', default=5000,24 unmodified lines589 Flask is enabled and disabled otherwise.590 """591 from werkzeug.serving import run_simple592 515- # Set a global flag that indicates that we were invoked from the516- # command line interface provided server command. This is detected517- # by Flask.run to make the call into a no-op. This is necessary to518- # avoid ugly errors when the script that is loaded here also attempts519- # to start a server.520- os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'521-593 debug = get_debug_flag()594 if reload is None:595 reload = bool(debug)596 if debugger is None:146 unmodified linesadded:tests/test_apps/.env+3 added
1+FOO=env2+SPAM=13+EGGS=2added:tests/test_apps/.flaskenv+3 added
1+FOO=flaskenv2+BAR=bar3+EGGS=0modified:tests/test_cli.py+65 added-8 removed
17 unmodified lines18 from functools import partial19 20 import click21 import pytest22+from _pytest.monkeypatch import notset23 from click.testing import CliRunner24 25 from flask import Flask, current_app25-from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \26- find_best_app, get_version, locate_app, prepare_import, with_appcontext26+from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, \27+ find_best_app, get_version, load_dotenv, locate_app, prepare_import, \28+ with_appcontext29 30+cwd = os.getcwd()31+test_path = os.path.abspath(os.path.join(32+ os.path.dirname(__file__), 'test_apps'33+))34 35+36+@pytest.fixture(autouse=True)37+def manage_os_environ(monkeypatch):38+ # can't use monkeypatch.delitem since we don't want to restore a value39+ os.environ.pop('FLASK_APP', None)40+ os.environ.pop('FLASK_DEBUG', None)41+ # use monkeypatch internals to force-delete environ keys42+ monkeypatch._setitem.extend((43+ (os.environ, 'FLASK_APP', notset),44+ (os.environ, 'FLASK_DEBUG', notset),45+ (os.environ, 'FLASK_RUN_FROM_CLI', notset),46+ ))47+48+49 @pytest.fixture50 def runner():51 return CliRunner()52 91 unmodified lines144 145 pytest.raises(NoAppException, find_best_app, script_info, Module)146 147 128-cwd = os.getcwd()129-test_path = os.path.abspath(os.path.join(130- os.path.dirname(__file__), 'test_apps'131-))132-133-148 @pytest.mark.parametrize('value,path,result', (149 ('test', cwd, 'test'),150 ('test.py', cwd, 'test'),151 ('a/test', os.path.join(cwd, 'a'), 'test'),275 unmodified lines427 output = invoke(['routes']).output428 assert 'GET, HEAD, OPTIONS, POST' not in output429 output = invoke(['routes', '--all-methods']).output430 assert 'GET, HEAD, OPTIONS, POST' in output431+432+433+need_dotenv = pytest.mark.skipif(434+ dotenv is None, reason='dotenv is not installed'435+)436+437+438+@need_dotenv439+def test_load_dotenv(monkeypatch):440+ # can't use monkeypatch.delitem since the keys don't exist yet441+ for item in ('FOO', 'BAR', 'SPAM'):442+ monkeypatch._setitem.append((os.environ, item, notset))443+444+ monkeypatch.setenv('EGGS', '3')445+ monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))446+ load_dotenv()447+ assert os.getcwd() == test_path448+ # .flaskenv doesn't overwrite .env449+ assert os.environ['FOO'] == 'env'450+ # set only in .flaskenv451+ assert os.environ['BAR'] == 'bar'452+ # set only in .env453+ assert os.environ['SPAM'] == '1'454+ # set manually, files don't overwrite455+ assert os.environ['EGGS'] == '3'456+457+458+@need_dotenv459+def test_dotenv_path(monkeypatch):460+ for item in ('FOO', 'BAR', 'EGGS'):461+ monkeypatch._setitem.append((os.environ, item, notset))462+463+ cwd = os.getcwd()464+ load_dotenv(os.path.join(test_path, '.flaskenv'))465+ assert os.getcwd() == cwd466+ assert 'FOO' in os.environ467+468+469+def test_dotenv_optional(monkeypatch):470+ monkeypatch.setattr('flask.cli.dotenv', None)471+ monkeypatch.chdir(test_path)472+ load_dotenv()473+ assert 'FOO' not in os.environmodified:.gitignore+2 added
1 .DS_Store2+.env3+.flaskenv4 *.pyc5 *.pyo6 env7 env*14 unmodified linesmodified:.travis.yml+5 added
31 unmodified lines32 33 cache:34 - pip35 36+branches:37+ only:38+ - master39+ - /^.*-maintenance$/40+41 notifications:42 email: false43 irc:44 channels:5 unmodified linesmodified:CHANGES+4 added
99 unmodified lines100 101 - The ``request.json`` property is no longer deprecated. (`#1421`_)102 - Support passing an existing ``EnvironBuilder`` or ``dict`` to103 ``test_client.open``. (`#2412`_)104+- The ``flask`` command and ``app.run`` will load environment variables using105+ from ``.env`` and ``.flaskenv`` files if python-dotenv is installed.106+ (`#2416`_)107 108 .. _#1421: https://github.com/pallets/flask/issues/1421109 .. _#1489: https://github.com/pallets/flask/pull/1489110 .. _#1621: https://github.com/pallets/flask/pull/162121 unmodified lines132 .. _#2373: https://github.com/pallets/flask/pull/2373133 .. _#2385: https://github.com/pallets/flask/issues/2385134 .. _#2412: https://github.com/pallets/flask/pull/2412135 .. _#2414: https://github.com/pallets/flask/pull/2414136+.. _#2416: https://github.com/pallets/flask/pull/2416137 138 Version 0.12.2139 --------------140 617 unmodified linesmodified:setup.py+2 added
73 unmodified lines74 'itsdangerous>=0.21',75 'click>=4.0',76 ],77 extras_require={78+ 'dotenv': ['python-dotenv'],79 'dev': [80 'blinker',81+ 'python-dotenv',82 'greenlet',83 'pytest>=3',84 'coverage',85 'tox',27 unmodified linesmodified:tox.ini+2 added-1 removed
13 unmodified lines14 pytest>=315 coverage16 greenlet17 blinker18+ python-dotenv19 20 lowest: Werkzeug==0.921 lowest: Jinja2==2.422 lowest: itsdangerous==0.2144 unmodified lines67 skip_install = true68 deps = detox69 commands =70 detox -e py{36,35,34,33,27,26,py},py{36,27,py}-simplejson,py{36,33,27,26,py}-devel,py{36,33,27,26,py}-lowest70- tox -e coverage-report71+ tox -e docs-html,coverage-report