1. 라이브러리 설치

https://django-environ.readthedocs.io/en/latest/

 

Welcome to Django-environ’s documentation! — Django-environ 0.4.4 documentation

Value from environment or default (if set)

django-environ.readthedocs.io

pip install django-environ

2. .env 파일 생성

settings.py 위치에 .env 파일 생성

DEBUG=on
SECRET_KEY=your-secret-key
DATABASE_URL=psql://urser:un-githubbedpassword@127.0.0.1:8458/database
SQLITE_URL=sqlite:///my-local-sqlite.db
CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213
REDIS_URL=rediscache://127.0.0.1:6379/1?client_class=django_redis.client.DefaultClient&password=ungithubbed-secret

3. settings.py 에서 불러오기

import os, environ
env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()

4. 환경변수 불러오기

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

# Parse database connection url strings like psql://user:pass@127.0.0.1:8458/db
DATABASES = {
    # read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found
    'default': env.db(),
    # read os.environ['SQLITE_URL']
    'extra': env.db('SQLITE_URL', default='sqlite:////tmp/my-tmp-sqlite.db')
}

CACHES = {
    # read os.environ['CACHE_URL'] and raises ImproperlyConfigured exception if not found
    'default': env.cache(),
    # read os.environ['REDIS_URL']
    'redis': env.cache('REDIS_URL')
}

5. gitignore 에 .env 추가

728x90

'Study > Django' 카테고리의 다른 글

[Django] decorator  (0) 2021.05.25
[Django] code formatting black 설치 및 적용  (0) 2021.05.20
[Django] Views, Generic Views, Viewset  (0) 2021.05.11
[Django] settings.py - cors, static path  (0) 2021.05.11
[Django] Serializers  (0) 2021.05.11

+ Recent posts