- Saved searches
- Use saved searches to filter your results more quickly
- License
- theskumar/python-dotenv
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Переменные окружения для Python проектов
- Конфигурационные файлы
- Переменные окружения
- Библиотека python-dotenv
- Утилита direnv
- Создадим новую папку для проекта:
- Покажем, что переменная окружения FLASK_APP не загружена:
- Запишем переменные окружения в файл .envrc :
- Для обеспечения безопасности, после создания или изменения файла .envrc , нужно выполнить подтверждение с помощью команды direnv allow:
- Покажем, что переменная окружения загружена:
- При выхода из папки с проектом переменные окружения выгружаются
- и становятся снова не заданными
- Работа с виртуальным окружением в direnv
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.
License
theskumar/python-dotenv
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Python-dotenv reads key-value pairs from a .env file and can set them as environment variables. It helps in the development of applications following the 12-factor principles.
If your application takes its configuration from environment variables, like a 12-factor application, launching it in development is not very practical because you have to set those environment variables yourself.
To help you with that, you can add Python-dotenv to your application to make it load the configuration from a .env file when it is present (e.g. in development) while remaining configurable via the environment:
from dotenv import load_dotenv load_dotenv() # take environment variables from .env. # Code of your application, which uses environment variables (e.g. from `os.environ` or # `os.getenv`) as if they came from the actual environment.
By default, load_dotenv doesn’t override existing environment variables.
To configure the development environment, add a .env in the root directory of your project:
The syntax of .env files supported by python-dotenv is similar to that of Bash:
# Development settings DOMAIN=example.org ADMIN_EMAIL=admin@$ ROOT_URL=$ /app
If you use variables in values, ensure they are surrounded with < and >, like $ , as bare variables such as $DOMAIN are not expanded.
You will probably want to add .env to your .gitignore , especially if it contains secrets like a password.
See the section «File format» below for more information about what you can write in a .env file.
Load configuration without altering the environment
The function dotenv_values works more or less the same way as load_dotenv , except it doesn’t touch the environment, it just returns a dict with the values parsed from the .env file.
from dotenv import dotenv_values config = dotenv_values(".env") # config =
This notably enables advanced configuration management:
import os from dotenv import dotenv_values config = < **dotenv_values(".env.shared"), # load shared development variables **dotenv_values(".env.secret"), # load sensitive variables **os.environ, # override loaded values with environment variables >
Parse configuration as a stream
load_dotenv and dotenv_values accept streams via their stream argument. It is thus possible to load the variables from sources other than the filesystem (e.g. the network).
from io import StringIO from dotenv import load_dotenv config = StringIO("USER=foo\nEMAIL=foo@example.org") load_dotenv(stream=config)
Load .env files in IPython
You can use dotenv in IPython. By default, it will use find_dotenv to search for a .env file:
You can also specify a path:
%dotenv relative/or/absolute/path/to/.env
A CLI interface dotenv is also included, which helps you manipulate the .env file without manually opening it.
$ pip install "python-dotenv[cli]" $ dotenv set USER foo $ dotenv set EMAIL foo@example.org $ dotenv list USER=foo EMAIL=foo@example.org $ dotenv list --format=json < "USER": "foo", "EMAIL": "foo@example.org" > $ dotenv run -- python foo.py
Run dotenv —help for more information about the options and subcommands.
The format is not formally specified and still improves over time. That being said, .env files should mostly look like Bash files.
Keys can be unquoted or single-quoted. Values can be unquoted, single- or double-quoted. Spaces before and after keys, equal signs, and values are ignored. Values can be followed by a comment. Lines can start with the export directive, which does not affect their interpretation.
It is possible for single- or double-quoted values to span multiple lines. The following examples are equivalent:
FOO="first line second line"
FOO="first line\nsecond line"
A variable can have no value:
It results in dotenv_values associating that variable name with the value None (e.g. . load_dotenv , on the other hand, simply ignores such variables.
This shouldn’t be confused with FOO= , in which case the variable is associated with the empty string.
Python-dotenv can interpolate variables using POSIX variable expansion.
With load_dotenv(override=True) or dotenv_values() , the value of a variable is the first of the values defined in the following list:
- Value of that variable in the .env file.
- Value of that variable in the environment.
- Default value, if provided.
- Empty string.
With load_dotenv(override=False) , the value of a variable is the first of the values defined in the following list:
- Value of that variable in the environment.
- Value of that variable in the .env file.
- Default value, if provided.
- Empty string.
- Honcho — For managing Procfile-based applications.
- django-dotenv
- django-environ
- django-environ-2
- django-configuration
- dump-env
- environs
- dynaconf
- parse_it
- python-decouple
This project is currently maintained by Saurabh Kumar and Bertrand Bonnefoy-Claudet and would not have been possible without the support of these awesome people.
About
Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.
Переменные окружения для Python проектов
При разработки web-приложения или бота мы часто имеем дело с какой-либо секретной информацией, различными токенами и паролями (API-ключами, секретами веб-форм). «Хардкодить» эту информацию, а тем более сохранять в публично доступной системе контроля версий это очень плохая идея.
# Плохая практика. Не делай так. API_KEY = 'very_secret_password'
Конфигурационные файлы
Самый простой путь решения данной проблемы, это создание отдельного конфигурационного файла со всей чувствительной информацией и добавление его в .gitignore . Минус такого подхода в том, что в гит нужно держать ещё и шаблон конфигурационного файла и не забывать его периодически обновлять.
# Уже лучше. from config import API_KEY app = Flask(__name__) app.config['API_KEY'] = API_KEY
Переменные окружения
Более продвинутый подход, это использование переменных окружения. Переменные окружения это именованные переменные, содержащие текстовую информацию, которую могут использовать запускаемые программы. Например, чтобы запустить flask-приложение, вначале нужно указать в переменной окружения FLASK_APP имя нашего приложения:
$ export FLASK_APP=hello.py $ flask run * Running on http://127.0.0.1:5000/
С помощью переменных окружения можно получать различные параметры приложение и секретные ключи:
import os app.config['API_KEY'] = os.environ.get('API_KEY')
Библиотека python-dotenv
Чтобы не задавать каждый раз вручную переменные окружения при новом запуске терминала, можно воспользоваться пакетом python-dotenv. Он позволяет загружать переменные окружения из файла .env в корневом каталоге приложения.
Устанавливаем пакет:
Теперь можно создать файл .env со всеми переменными среды, которые необходимы вашему приложению. Важно, добавьте .env -файл в .gitignore , не храните его в системе контроля версий.
import os from dotenv import load_dotenv dotenv_path = os.path.join(os.path.dirname(__file__), '.env') if os.path.exists(dotenv_path): load_dotenv(dotenv_path)
Этот .env-файл можно использовать для всех переменных конфигурации, но его нельзя использовать для переменных среды FLASK_APP и FLASK_DEBUG , так как они необходимы уже в процессе начальной загрузки приложения.
Утилита direnv
Переменные среды могут быть автоматически загружены при входе в папку с проектом, это особенно удобно при работе с несколькими проектами одновременно. Сделать это позволяет утилита direnv. Direnv — это менеджер переменных среды для терминала, поддерживает bash, zsh, tcsh и др. оболочки. Позволяет автоматически загружать и выгружать переменные среды в зависимости от вашего текущего каталога. Это позволяет иметь переменные среды, специфичные для каждого проекта. Перед каждым приглашением проверяется наличие файла .envrc в текущем и родительском каталогах. Если файл существует, он загружается в подшаблон bash, и все экспортированные переменные затем захватываются direnv, а затем становятся доступными для оболочки.
sudo apt-get install direnv
Далее необходимо внести изменения для настройки нашей оболочки, для bash необходимо в конец файла ~/.bashrc добавить следующее и перезапустить консоль:
Создадим новую папку для проекта:
$ mkdir ~/my-project $ cd ~/my-project
Покажем, что переменная окружения FLASK_APP не загружена:
Запишем переменные окружения в файл .envrc :
$ echo export FLASK_APP=hello.py > .envrc .envrc is not allowed
Для обеспечения безопасности, после создания или изменения файла .envrc , нужно выполнить подтверждение с помощью команды direnv allow:
$ direnv allow . direnv: reloading direnv: loading .envrc direnv export: +FLASK_APP
Покажем, что переменная окружения загружена:
При выхода из папки с проектом переменные окружения выгружаются
и становятся снова не заданными
Работа с виртуальным окружением в direnv
Кроме загрузки переменных окружения, утилита direnv позволяет также работать с виртуальным окружением для Python.
Виртуальное окружение позволяет использовать для отдельные проектов разные версии интерпретатора python и пакетов библиотек. Существует несколько способов создания виртуального окружения для python, здесь мы рассмотрим модуль venv, для другие варианты описаны в документации к direnv.
Чтобы использовать venv для автоматического создания и активирования виртуального окружения, необходимо добавить в файл ~/.config/direnv/direnvrc следующий код (см. документацию).
Создание виртуального окружения
Если в файл .envrc добавить строчку
то при переходе в папку будет direnv создаст виртуальное окружение в папке direnv, например .direnv/python-venv-3.7.3 .
Чтобы создать виртуальное окружение с другим путем, например в более привычной папке venv, надо задать переменную VIRTUAL_ENV :
Таким же способом можно подключать уже созданное виртуальное окружение.
Работа с разными версиями Python
Для установки отличной от системной версии python, нужно использовать команду:
layout python-venv python3.6
Создаем строку приглашения bash (PS1)
В отличие от ручной активации виртуального окружения, в нашем случае строка приглашения bash (PS1) не будет изменена (обычно она выглядит как (venv) user@comp:~$ ). Чтобы вернуть показ активации виртуального окружения в консоли нужно в файл ~/.bashrc добавить следующий код:
show_virtual_env() < if [[ -n "$VIRTUAL_ENV" && -n "$DIRENV_DIR" ]]; then echo "($(basename $VIRTUAL_ENV))" fi >export -f show_virtual_env PS1='$(show_virtual_env)'$PS1
Пример файла настройки файла .envrc
Вот так может выглядеть файл .envrc настроенный для разработки flask-приложения:
export VIRTUAL_ENV=venv layout python-venv export FLASK_APP=app.py export FLASK_DEBUG=1
Это позволяет автоматически активировать виртуальное окружение и загрузить переменные окружения при входе в папку с проектом.