Repository navigation
Expand file tree
/
Copy pathconfig.py
More file actions
47 lines (36 loc) · 1.41 KB
/
Copy pathconfig.py
File metadata and controls
47 lines (36 loc) · 1.41 KB
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
40
41
42
43
44
45
46
47
"""Tiny config helper.
Reads optional secrets/settings from a local ``config.ini`` (gitignored) with an
environment-variable fallback, so a key can be supplied either way. Nothing here
is required — every lookup degrades gracefully to a default when neither the file
nor the env var is set.
config.get("virustotal", "api_key", env="VIRUSTOTAL_API_KEY")
Copy ``config.ini.example`` to ``config.ini`` and fill in what you want.
"""
from __future__ import annotations
import configparser
import os
CONFIG_PATH = os.environ.get(
"PCAPGRAPH_CONFIG", os.path.join(os.path.dirname(__file__), "config.ini")
)
_parser: configparser.ConfigParser | None = None
def _load() -> configparser.ConfigParser:
global _parser
if _parser is None:
_parser = configparser.ConfigParser()
if os.path.exists(CONFIG_PATH):
try:
_parser.read(CONFIG_PATH)
except configparser.Error:
pass
return _parser
def get(section: str, key: str, env: str | None = None, default: str = "") -> str:
"""Return a setting. Env var (if given and set) wins, then config.ini, then
the default. Always returns a stripped string."""
if env:
val = os.environ.get(env)
if val:
return val.strip()
try:
return _load().get(section, key).strip()
except (configparser.NoSectionError, configparser.NoOptionError):
return default