Intro
종종 config.ini 와 같은 파일을 본 적이 있을 것입니다. 이러한 ini 파일은 보통 설정값들을 손쉽게 읽고 쓸 수 있도록 하기 위해 사용하는 파일입니다.
애플리케이션을 개발할 때 서비스의 여러 설정 정보들 (예를 들어 서빙 포트 번호나 DB 접속 정보와 같은 것들)을 소스 코드와 분리해 관리하는 것은 매우 중요합니다. 설정 정보를 코드 내에 하드코딩 하면, 추후 설정 변경 시마다 코드를 수정해야 하는 불편함이 생기므로, 설정을 담은 파일을 별도로 관리하죠.
이번 포스팅에서는 config.ini 설정파일을 작성하는 방법과 configparser 모듈을 이용해 소스코드와 분리된 설정파일에서 쉽게 설정값들을 불러와 사용하는 방법을 알아보도록 하겠습니다.
config.ini 파일
- config 파일은 섹션(section), 키-값 쌍, 주석 으로 구성됩니다.
| 항목 | 설명 |
|---|---|
| 섹션 section |
- 대괄호 []로 섹션의 이름을 감싸서 정의한다.- 하나의 설정파일에서 관련이 있는 여러 설정값들을 그룹화하는 단위 - 여러 파일을 담은 폴더와 같은 느낌 - 섹션 아래에는 해당 섹션에 속하는 키-값 쌍들이 위치한다. |
| 키-값 쌍 key-value |
- 키 = 값과 같이 작성한다.- 키 : 설정의 명칭, 이름 - 해당 설정의 값 |
| 주석 comment |
- 세미콜론(;) 혹은 해시(#) 기호로 시작하는 줄은 주석으로 처리됨 |
1
2
3
4
5
6
7
8
9
10
11
12
13
[fastapi]
bind=0.0.0.0
port=8080
timeout=30
[gemini.genai]
api.api_key=12523151
api.auth.user=user
api.auth.password=password
[setting]
mode.debug=1
mode.terminal=no
configparser
설치
- configparser 모듈은 파이썬 기본 내장 모듈입니다.
- 따라서 별도의 설치가 필요하지 않습니다.
기본 사용법
- (1) ConfigParser 인스턴스 생성 :
ConfigParser() - (2) 설정파일 읽기 : ConfigParser의 인스턴스의
read(path)메서드. 인자는 설정파일 경로 - (3) 설정값 가져오기 : 설정파일을 읽은 ConfigParser 인스턴스를 딕셔너리 형태로 생각하고 값을 읽어들임
1
2
3
4
5
6
7
8
9
10
import configparser
config = configparser.ConfigParser()
config.read('path/of/config.ini')
serving_url = f'http://{config["fastapi"]["bind"]}:{config["fastapi"]["port"]}'
gemini_api_key = config['gemini.genai']['api.api_key']
print(serving_url)
print(gemini_api_key)
1
2
http://0.0.0.0:8080
12523151
설정값을 읽은 ConfigParser 인스턴스
- 설정값을 읽은 ConfigParser 인스턴스의 내부를 출력해보면 아래와 같음
1
2
3
4
5
print("## config")
print(config)
print("## config.__dcit__")
print(config.__dict__)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
## config
<configparser.ConfigParser object at 0x102e54380>
## config.__dcit__
{'_dict': <class 'dict'>,
'_sections': {
'fastapi': {
'bind': '0.0.0.0',
'port': '8080',
'timeout': '30'
},
'gemini.genai': {
'api.api_key': '12523151',
'api.auth.user': 'user',
'api.auth.password': 'password'
},
'setting':{
'mode.debug': '1',
'mode.terminal': 'no'
},
},
'_defaults': {},
'_converters': <configparser.ConverterMapping object at 0x102e54350>,
'_proxies': {
'DEFAULT': <Section: DEFAULT>,
'fastapi': <Section: fastapi>,
'gemini.genai': <Section: gemini.genai>,
'setting': <Section: setting>
},
'_delimiters': ('=', ':'),
'_optcre': re.compile('\n (?P<option>.*?) # very permissive!\n \\s*(?P<vi>=|:) \\s* # any number of space/tab,\n # followed by any of t, re.VERBOSE),
'_comment_prefixes': ('#', ';'),
'_inline_comment_prefixes': (),
'_strict': True,
'_allow_no_value': False,
'_empty_lines_in_values': True,
'default_section': 'DEFAULT',
'_interpolation': <configparser.BasicInterpolation object at 0x102f007a0>
}
읽어들인 설정값 가져오기
딕셔너리 인덱싱 dictionary indexing
abc["abc"]와 같이 딕셔너리 인덱싱으로 설정값을 가져오는 방법
1
print(config["fastapi"]["bind"])
1
0.0.0.0
get 메서드
get메서드를 통해 설정값을 가져오는 방법
1
print(config.get("fastapi", "bind"))
1
0.0.0.0
getboolean 메서드
- 설정값을 불러와 bool 형태로 변환하는 메서드
1
2
print(config.getboolean("setting", "mode.debug"))
print(config.getboolean("setting", "mode.terminal"))
1
2
True
False
| 구분 | 사용 가능한 값 |
|---|---|
| True | “1”, “yes”, “true”, “on” |
| False | “0”, “no”, “false”, “off” |
Reference
https://docs.python.org/ko/3/library/configparser.html
https://docs.python.org/ko/3/library/configparser.html#supported-datatypes
점프 투 파이썬
Comments