본문 바로가기

파이썬 - python

장고 환경 변수 분리 django Separating environment [.env / secrets.json]

1. 외부 패키지 이용 방법

(환경변수 분리 패키지 설치)

pip install django-dotenv

 

(환경변수 파일 생성 변수 작성)

manage.py 동일 위치, 파일명 : .env
project dir > .env

EMAIL_HOST_USER = "won-ideal"
EMAIL_HOST_PASSWORD = "idealkr!"
  • key = value 형식, JSON X

(setting.py 추가)

...

EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD")
  • .env 파일에 키값 호출

(manage.py 선언)

manage.py

...
import dotenv

...

if __name__ == "__main__":
    dotenv.read_dotenv()
    main()

2. json 파일 이용 방법

(secrets.json 파일 생성)

JSON 형식의 파일 생성

{
  "SECRET_KEY": "...",
  "API_SECRET": "..."
}
  • { "Key": "Value" } 형식 작성
  • 라인간 ,(콤마) 필수

(settings.py 수정)

...
import json
...

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: keep the secret key used in production secret!
secret_file = os.path.join(BASE_DIR, 'secrets.json')

with open(secret_file) as f:
    secrets = json.loads(f.read())


# Keep secret keys in secrets.json
def get_secret(setting, secrets=secrets):
    try:
        return secrets[setting]
    except KeyError:
        error_msg = "Set the {0} environment variable".format(setting)
        raise ImproperlyConfigured(error_msg)


SECRET_KEY = get_secret("SECRET_KEY")
  • 필요 값 사용 get_secret("secrets.json file key")