상세 컨텐츠

본문 제목

파이썬 config 파일의 민감정보 분리방법

파이썬/Snippets

by amanda.hyon 2021. 3. 18. 21:04

본문

1. json 파일로 분리하는 방법

  • 파이썬 예제 코드
import os, json
import pymysql

BASE_DIR = "./"
secret_file = os.path.join(BASE_DIR, 'secrets.json')

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

def get_secret(setting, secrets=secrets):
    try:
        return secrets[setting]
    except KeyError:
        err_msg = f"set the {setting} enviroment variable"
        raise print(err_msg)
        
db_host = get_secret("DB_HOST")
db_user = get_secret("DB_USER")
db_pass = get_secret("DB_PASS")
db_port = get_secret("DB_PORT")
db_name = get_secret("DB_NAME")

db_conn = pymysql.connect(
    host=db_host,
    user=db_user,
    password=db_pass,
    db=db_name,
    charset='utf8'
)

curs = db_conn.cursor()

 

  • 민감정보가 담긴 json 파일 (secretes.json)
{
  "DB_HOST" : "localhost",
  "DB_USER" : "root",
  "DB_PASS" : "패스워드",
  "DB_NAME" : "서버이름",
  "DB_PORT" : "3306",
}

 

2. configparser를 이용하여 민감 정보를 분리하는 방법

  • 파이썬 예제 코드
import pymysql
import configparser

config = configparser.ConfigParser()
config.read('config.ini')
db_host = config['DB']['HOST']
db_user = config['DB']['USER']
db_pass = config['DB'].get("PASS", "default password")
db_name = config['DB'].get("NAME", False)

db_conn = pymysql.connect(
    host=db_host,
    user=db_user,
    password=db_pass,
    db=db_name,
    charset='utf8'
)

 

  • config.ini 파일 설정내용
[DB]
HOST = 10.10.10.16
NAME = my_db_server
USER = root
PASS = password!!!

[DRIVER]
EXE = C:\\Users\\cooky\\PycharmProjects\\ott_crawling\\chromedriver_win32\\chromedriver.exe
OPTION = --disable-extensions --disable-gpu --no-sandbox --incognito --disable-application-cache

관련글 더보기

댓글 영역