Переменные окружения python django

Переменные окружения в Django

Одним из способов защиты ваших секретных ключей от внешних зрителей и кодовой базы является использование переменных окружения.

В Python вы можете использовать os.getenv(‘THE_KEY’) или os.environ.get(‘THE_KEY’) .
Например, при работе на Python вы можете изменить команду Django на поиск значения SECRET_KEY .

SECRET_KEY = os.getenv("SECRET_KEY") # or SECRET_KEY = os.environ.get("SECRET_KEY") 

Эти строки приведут к программному сбою, если в файле .env проекта отсутствует переменная SECRET_KEY .

Чтобы избежать этого, вы можете передать в качестве второго аргумента значение по умолчанию.

SECRET_KEY = os.getenv( "SECRET_KEY", "django-insecure-r(6dd3yaw_05m5kxki1vb^r6v@x^-g#zi_to7487*!)08oxwf)" ) 

Эти методы весьма полезны, если вы хотите использовать env-вары в Django. В любом случае, вы также можете проверить django-environ пакет Python, который позволяет вам использовать двенадцатифакторную методологию для настройки вашего Django приложения с помощью переменных окружения.

Статья опубликована с помощью bloggu.io. Попробуйте бесплатно.

Источник

Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site’s growth and development.

Using Environment Variables In Django

An environment variable is a variable whose value is set outside the program, typically through a functionality built into the operating system. An environment variable is made up of a name/value pair. Environment variables help us keep secrets (for example, Passwords, API tokens, and so on) out of version control, therefore, they are considered an integral part of the popular Twelve-Factor App Design methodology and a Django best practice because they allow a greater level of security and simpler local/production configurations. Also, environment variables provide a greater degree of flexibility for switching between local development setup and production setup. Therefore Adding environment variables is a necessary step for any truly professional Django project.

Creating Environment Variables

Create a .env file in the same directory where settings.py resides and add the following key-value pair inside the file.

SECRET_KEY=0x!b#(1*cd73w$&azzc6p+essg7v=g80ls#z&xcx*mpemx&@9$ DATABASE_NAME=db_name DATABASE_USER=db_user DATABASE_PASSWORD=password DATABASE_HOST=localhost DATABASE_PORT=5432

We will use django-environ for managing environment variables inside our project. So let’s install the package.

pip install django-environ
import environ env = environ.Env() # reading .env file environ.Env.read_env() # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env("SECRET_KEY") DATABASES = < 'default': < 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("DATABASE_NAME"), 'USER': env("DATABASE_USER"), 'PASSWORD': env("DATABASE_PASSWORD"), 'HOST': env("DATABASE_HOST"), 'PORT': env("DATABASE_PORT"), >>

Save the file and run the server everything should be working smoothly. Additionally, you can also provide default values as follows.

SECRET_KEY = env("SECRET_KEY", default="unsafe-secret-key")

Don’t forget to add .env in your .gitignore also, it’s advisable to create a .env.example with a template of all the variables required for the project.

Читайте также:  Add css inside css

Источник

How to use Environment Variables in Django

In a Django project, there is information that needs to be kept secret like a Secret key, a Database username and password, and API keys. This is because their exposure to foreign parties can put your project at risk of security attacks. In Django projects that are not meant for deployment, this may not be a big issue but for production-level projects, it is mandatory to keep the information safe. In Django, we do that by using environment variables which are variables stored in the system of a computer so that no one can access them. This post is going to elaborate more on how to use environment variables in a Django project.

Table of Contents: use Environment Variables in Django

How to use Environment Variables in Django

Follow these steps to use Environment variables in a Django project:

  1. Install python-dotenv
  2. Import and Initialise python-dotenv in settings.py
  3. Create a .env file at the root of the Project
  4. Set Environment Variables in .env file
  5. Assign the Environment Variables in the settings.py
  6. Add the .env file to .gitignore file

Here are the detailed steps to set environment variables in Django:

Step 1: Install python-dotenv

The tool we are going to use to set our environment variables in this post is python-dotenv.

Python-dotenv is able to function by reading key-value pairs from a .env file, and it can then use those pairs to set environment variables.

To install it in your Django project, run the following command in the terminal of your Django project:

(env) $ pip install python-dotenv 

Once the command has been run, it’s now time to use it in the settings.py file of our Django project.

Читайте также:  Java lang string library

Step 2: Import and Initialise python-dotenv in settings.py

We start by importing python-dotenv in our settings.py file. At the top of settings.py file below the Path import, add the following 2 import statements and an initialisation statement:

from dotenv import load_dotenv import os load_dotenv()

load_dotenv is going to load our environment variables from the .env file. os is going to access the operating system since we’re saving these variables to the system of the computer.

Below the imports, we initialize dotenv by calling the load_dotenv() function.

We can now start using python_dotenv in the file.

Step 3: Create a .env file at the root of the Project

At the root of your Django project folder, create a new file called .env . Make sure you don’t miss the period at the beginning. Your project structure should look like this:

This is a special type of file. Your code editor should display it with an icon that is different from the rest. In VS Code, it is displayed as a gear icon.

Step 4: Set Environment Variables in .env file

Now it is time to declare all the variables that you want their values to be kept safe or secret. Such information can be passwords, secret keys, API keys, and so on. As an example, I will list a few variables that are important to keep safe. The list can be longer depending on your project:

SECRET_KEY=django-insecure-g6owp@47mbu33+nemhf$btj&6e7t&8)&n!uax1obkf-d)9$9*j DB_NAME=moviereviews DB_USER=root DB_PASS=hO5xY%00j

These are few of the variables you can add to the .env file.

Note that we don’t use quotes around strings because they will be converted automatically when they get loaded into the settings.py file.

Note that we also do not use spaces on both sides of the assignment operator because there is no need to.

You can learn more on how to declare environment variables using python_dotenv from it’s pypi page.

Step 5: Assign the Environment Variables in the settings.py

Now that our variables are in the .env file, its now time to replace the explicit values in the settings.py with the ones in the Django environment variable file.

We use environ from os as follows:

SECRET_KEY = os.environ.get('SECRET_KEY') #here . DATABASES = < 'default': < 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('DB_NAME'), #here 'USER': os.environ.get('DB_USER'), #here 'PASSWORD': os.environ.get('DB_PASS'), #here 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': , > >

We use the get() method to get the environment variable from the .env file.

Читайте также:  Argparse python 3 main

The DATABASES dictionary in this example has the configuration for the MySQL database.

To check if you’ve set the environment variables correctly, run the development server of your Django project.

Step 6: Add the .env file to .gitignore file

Since the .env file contains sensitive information about our Django project, it should also not be uploaded to a git repository. To do that, you have to add it to the list in the .gitignore file of your Django project. .gitignore is a file where you list all the files and directories you do not want to be uploaded to git.

Источник

Использование переменных окружения для конфигурирования Django

Крайне удобно, когда можно гибко управлять настройками своего приложения. Такими как подключение к базе данных, какие-то магические константы или ключи шифрования приложения. В Django есть механизм конфигурационных файлов, однако они не удобны тем, что они попадают в репозиторий. А это, во-первых, создаёт смешение отвественности. Репозиторий нужен для хранения исходных кодов, а не данных доступа и настроек сред. А, во-вторых, если одно и то же приложение используется в нескольких окружениях (даже дев/тест/прод) то возникает головная боль с сопровождением этих настроек и поддержкой их в актуальном состоянии. Решением этой проблемы могут стать переменные окружения.

Что такое переменные окружения

Если не вдаваться глубоко, то переменные окружения это значения, которые могут меняться в зависимости от того, где запущена программа. Хорошим примером, знакомым для всех веб-разработчиков, являются переменные окружения CGI, в которых хранятся значения домена, по которому произошёл запрос, IP адреса сервера и прочие любопытные значения. Другим примером может быть значение текущей директории в линуксе или виндовс в терминале. Которое тоже можно получить из значений переменных окружения.

Переменными окружения обычно конфигурируются параметры работы приложения в CI/CD средах, в Docker-контейнерах, в различных сессиях терминала. Удобно просто настраиваить приложение у каждого клиента через переменные окружения и в репозитории хранить только исходный код.

Примеры переменных окружения

Переменные окружения устанавливаются или через интерфейс операционной системы (системное API или через интерфейс/конфигурацию), через команды терминала или конфигурационным файлом. К примеру, просмотреть список в терминале Linux/Mac можно с помощью команды env в терминале

Источник

Оцените статью