본문 바로가기
웹(Web)/Django

[Django] Secret key 분리하기

by hyezzisss 2022. 1. 16.

django 프로젝트를 깃허브에 커밋 후 메일로

 

GitGuardian has detected the following
Django Secret Key exposed within your GitHub account.

 

와 같은 메시지를 받았다.

Secret Key가 github에 노출되었다는 의미라고 한다.

 

분리 방법

1. 먼저 프로젝트 폴더에서 가장 바깥쪽에 json파일을 만들고 아래와 같이 secret key를 작성하기

(나와 같은 경우는 secrets.json로 작성했다)

{
    "SECRET_KEY" : "(본인의 SECRET KEY)"
}

 

2. settings.py에 다음과 같이 작성하기

(secret key를 밖으로 분리했으므로 json 파일을 읽어들이는 코드이다)

import os, json 
from django.core.exceptions import ImproperlyConfigured 

secret_file = os.path.join(BASE_DIR, 'secrets.json') #secrets.json 불러오기

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

def get_secret(setting, secrets=secrets): #예외 처리
    try:
        return secrets[setting]
    except KeyError:
        error_msg = "Set the {} environment variable".format(setting)
        raise ImproperlyConfigured(error_msg)

SECRET_KEY = get_secret("SECRET_KEY")

 

3. .gitignore 파일에 json파일 추가하기

secrets.json

 

4. 이미 secrets.json을 추가하고 올렸거나 gitignore이 반영이 되지 않는다면 아래와 같이 시도하기

git rm -r --cached .
git add .
git commit -m "commit message"
git push

 

 

 

 

 

 

 

'웹(Web) > Django' 카테고리의 다른 글

[Django] 1. 프로젝트 생성 및 구동 방법  (0) 2022.01.09

댓글