Skip to content
Myr

load env vars using python-dotenv

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

authored by David Lord · committed by David Lord · parent 77b98a2 · 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

13 files+235 added−42 removed

modified:docs/api.rst+2 added
812 unmodified lines
813814.. autoclass:: ScriptInfo815 :members:816817.. autofunction:: load_dotenv818819.. autofunction:: with_appcontext820821.. autofunction:: pass_script_info822
6 unmodified lines
modified:docs/cli.rst+31 added-3 removed
95 unmodified lines
96Custom Commands97---------------9899If you want to add more commands to the shell script you can do this100easily. Flask uses `click`_ for the command interface which makes101creating custom commands very easy. For instance if you want a shell102command to initialize the database you can do this::100easily. For instance if you want a shell command to initialize the database you101can do this::102103 import click104 from flask import Flask105
26 unmodified lines
132 @app.cli.command(with_appcontext=False)133 def example():134 pass135136137.. _dotenv:138139Loading Environment Variables From ``.env`` Files140-------------------------------------------------141142If `python-dotenv`_ is installed, running the :command:`flask` command will set143environment variables defined in the files :file:`.env` and :file:`.flaskenv`.144This can be used to avoid having to set ``FLASK_APP`` manually every time you145open a new terminal, and to set configuration using environment variables146similar to how some deployment services work.147148Variables set on the command line are used over those set in :file:`.env`,149which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be150used for public variables, such as ``FLASK_APP``, while :file:`.env` should not151be committed to your repository so that it can set private variables.152153Directories are scanned upwards from the directory you call :command:`flask`154from to locate the files. The current working directory will be set to the155location of the file, with the assumption that that is the top level project156directory.157158The 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 in160production, you should call :func:`~flask.cli.load_dotenv` manually.161162.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme163164165Factory Functions166-----------------167168In case you are using factory functions to create your application (see
167 unmodified lines
modified:docs/installation.rst+3 added
39 unmodified lines
40* `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.4647.. _Blinker: https://pythonhosted.org/blinker/48.. _SimpleJSON: https://simplejson.readthedocs.io/49.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme5051Virtual environments52--------------------53
125 unmodified lines
modified:flask/app.py+27 added-15 removed
818 unmodified lines
819 """820 self.debug = debug821 self.jinja_env.auto_reload = self.templates_auto_reload822823 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.827828 Do not use ``run()`` in a production setting. It is not intended to829 meet security and performance requirements for a production server.
20 unmodified lines
850 Setting ``use_debugger`` to ``True`` without being in debug mode851 won't catch any exceptions because there won't be any to852 catch.853854 :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.868869 .. versionchanged:: 1.0870 If installed, python-dotenv will be used to load environment871 variables from :file:`.env` and :file:`.flaskenv` files.872873 .. versionchanged:: 0.10874 The default port is now picked from the ``SERVER_NAME`` variable.875855 :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 return883884 if load_dotenv:885 from flask.cli import load_dotenv886 load_dotenv()887888 if debug is not None:889 self._reconfigure_for_run_debug(bool(debug))890891 _host = '127.0.0.1'
1306 unmodified lines
modified:flask/cli.py+86 added-15 removed
6 unmodified lines
78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from __future__ import print_function1213import ast14import inspect15import os
6 unmodified lines
2223import click2425from . import __version__25from ._compat import iteritems, reraise26from ._compat import getargspec, iteritems, reraise27from .globals import current_app28from .helpers import get_debug_flag28from ._compat import getargspec2930try:31 import dotenv32except ImportError:33 dotenv = None343536class NoAppException(click.UsageError):37 """Raised if an application cannot be found or loaded."""3839
358 unmodified lines
398399 For information as of why this is useful see :ref:`custom-scripts`.400401 :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.409410 .. versionchanged:: 1.0411 If installed, python-dotenv will be used to load environment variables412 from :file:`.env` and :file:`.flaskenv` files.413 """414415 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 ())420421 if add_version_option:422 params.append(version_option)423424 AppGroup.__init__(self, params=params, **extra)425 self.create_app = create_app426 self.load_dotenv = load_dotenv427428 if add_default_commands:429 self.add_command(run_command)430 self.add_command(shell_command)
55 unmodified lines
486 traceback.print_exc()487 return sorted(rv)488489 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'495496 if self.load_dotenv:497 load_dotenv()498499 obj = kwargs.get('obj')500501 if obj is None:502 obj = ScriptInfo(create_app=self.create_app)503504 kwargs['obj'] = obj505 kwargs.setdefault('auto_envvar_prefix', 'FLASK')480 return AppGroup.main(self, *args, **kwargs)506 return super(FlaskGroup, self).main(*args, **kwargs)507508509def _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)) == other514515516def load_dotenv(path=None):517 """Load "dotenv" files in order of precedence to set environment variables.518519 If an env var is already set it is not overwritten, so earlier files in the520 list are preferred over later files.521522 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.525526 This is a no-op if `python-dotenv`_ is not installed.527528 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme529530 :param path: Load the file at this location instead of searching.531 :return: ``True`` if a file was loaded.532533 .. versionadded:: 1.0534 """535536 if dotenv is None:537 return538539 if path is not None:540 return dotenv.load_dotenv(path)541542 new_dir = None543544 for name in ('.env', '.flaskenv'):545 path = dotenv.find_dotenv(name, usecwd=True)546547 if not path:548 continue549550 if new_dir is None:551 new_dir = os.path.dirname(path)552553 dotenv.load_dotenv(path)554555 if new_dir and os.getcwd() != new_dir:556 os.chdir(new_dir)557558 return new_dir is not None # at least one file was located and loaded559560561@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 lines
589 Flask is enabled and disabled otherwise.590 """591 from werkzeug.serving import run_simple592515 # 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'521593 debug = get_debug_flag()594 if reload is None:595 reload = bool(debug)596 if debugger is None:
146 unmodified lines
added:tests/test_apps/.env+3 added
1FOO=env2SPAM=13EGGS=2
added:tests/test_apps/.flaskenv+3 added
1FOO=flaskenv2BAR=bar3EGGS=0
modified:tests/test_cli.py+65 added-8 removed
17 unmodified lines
18from functools import partial1920import click21import pytest22from _pytest.monkeypatch import notset23from click.testing import CliRunner2425from flask import Flask, current_app25from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \26 find_best_app, get_version, locate_app, prepare_import, with_appcontext26from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, \27 find_best_app, get_version, load_dotenv, locate_app, prepare_import, \28 with_appcontext2930cwd = os.getcwd()31test_path = os.path.abspath(os.path.join(32 os.path.dirname(__file__), 'test_apps'33))343536@pytest.fixture(autouse=True)37def 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 ))474849@pytest.fixture50def runner():51 return CliRunner()52
91 unmodified lines
144145 pytest.raises(NoAppException, find_best_app, script_info, Module)146147128cwd = os.getcwd()129test_path = os.path.abspath(os.path.join(130 os.path.dirname(__file__), 'test_apps'131))132133148@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 lines
427 output = invoke(['routes']).output428 assert 'GET, HEAD, OPTIONS, POST' not in output429 output = invoke(['routes', '--all-methods']).output430 assert 'GET, HEAD, OPTIONS, POST' in output431432433need_dotenv = pytest.mark.skipif(434 dotenv is None, reason='dotenv is not installed'435)436437438@need_dotenv439def 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))443444 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'456457458@need_dotenv459def test_dotenv_path(monkeypatch):460 for item in ('FOO', 'BAR', 'EGGS'):461 monkeypatch._setitem.append((os.environ, item, notset))462463 cwd = os.getcwd()464 load_dotenv(os.path.join(test_path, '.flaskenv'))465 assert os.getcwd() == cwd466 assert 'FOO' in os.environ467468469def 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.environ
modified:.gitignore+2 added
1.DS_Store2.env3.flaskenv4*.pyc5*.pyo6env7env*
14 unmodified lines
modified:.travis.yml+5 added
31 unmodified lines
3233cache:34 - pip3536branches:37 only:38 - master39 - /^.*-maintenance$/4041notifications:42 email: false43 irc:44 channels:
5 unmodified lines
modified:CHANGES+4 added
99 unmodified lines
100101- 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`_)107108.. _#1421: https://github.com/pallets/flask/issues/1421109.. _#1489: https://github.com/pallets/flask/pull/1489110.. _#1621: https://github.com/pallets/flask/pull/1621
21 unmodified lines
132.. _#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/2416137138Version 0.12.2139--------------140
617 unmodified lines
modified:setup.py+2 added
73 unmodified lines
74 '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 lines
modified:tox.ini+2 added-1 removed
13 unmodified lines
14 pytest>=315 coverage16 greenlet17 blinker18 python-dotenv1920 lowest: Werkzeug==0.921 lowest: Jinja2==2.422 lowest: itsdangerous==0.21
44 unmodified lines
67skip_install = true68deps = detox69commands =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