Merge branch 'md파일-수정'

This commit is contained in:
minaChoi committed 2026-08-31 15:18:54 +09:00
commit 7cab58e897
721 files changed
+877 -532

No files matched your search

@@ -0,0 +1,52 @@
# 복사해서 사용: cp config.local.toml.example config.local.toml
# 실제 config.local.toml 은 시크릿 포함이라 커밋하지 않는다(.gitignore: *.toml).
# 모든 서버는 APP_ENV=local 로 띄우며 이 파일을 읽는다.
[WebServerConfig]
server_name = "Web4aiServer"
port = 9800
process_count = 1
is_ssl = false
is_test = true
# 관리자 프론트 오리진 — CORS 허용. 쉼표로 여러 개.
# vite 는 3000 이 쓰이고 있으면 3001, 3002… 로 옮겨 뜨므로 개발 포트 대역을 함께 적어 둔다.
# 운영에서는 실제 도메인 하나만 남긴다.
client_url = "http://localhost:3000,http://localhost:3001,http://localhost:3002,http://localhost:3003,http://localhost:3004,http://localhost:3005"
landing_url = "" # 랜딩(마케팅 사이트). 없으면 빈값
[LogConfig]
print_console = true
log_level = "debug"
# DB Read/Write 분리. 도커 실행 시 host 는 docker-compose 의 DB_HOST 로 override.
# 관리형 DB(RDS/Aurora/Azure)는 host 에 엔드포인트, sslmode="require".
[MainDBConfig]
db_type = "postgresql"
name = "web4ai_db"
write_host = "127.0.0.1"
write_port = 5432
write_id = "<DB_USER>"
write_pw = "<DB_PASSWORD>"
read_host = "127.0.0.1"
read_port = 5432
read_id = "<DB_USER>"
read_pw = "<DB_PASSWORD>"
show_log = false
pool_size = 10
max_overflow = 20
sslmode = "" # 로컬: "" / 관리형 DB: "require"|"verify-ca"|"verify-full"
[JwtToken]
access_key = "<JWT_ACCESS_SECRET>"
refresh_key = "<JWT_REFRESH_SECRET>"
access_expire_min = 30
refresh_expire_day = 7
# 수집 파이프라인 외부 API 키. 빈값이면 해당 어댑터 비활성(서버는 그대로 뜬다).
# 배포에서 환경변수로만 주입하려면 여기는 비우고 PERPLEXITY_API_KEY 등을 env 로 넘긴다.
[ExternalApiConfig]
perplexity_api_key = "" # 채널 URL 발견
kakao_rest_api_key = "" # 동일 업소 검증(미발급)
naver_client_id = "" # 동일 업소 검증 — 네이버 지역검색
naver_client_secret = ""
gemini_api_key = "" # 사진 분류 · 카피 작성
tour_api_key = "" # 공공데이터포털 전국문화축제표준데이터 일반 인증키
@@ -0,0 +1,51 @@
# 복사해서 사용: cp config.test.toml.example config.test.toml
# 실제 config.test.toml 은 커밋하지 않는다(.gitignore: *.toml).
#
# ★ 이 파일이 없으면 `.venv/bin/pytest` 가 conftest import 단계에서 죽는다
# (server_configs 가 config.<APP_ENV>.toml 을 읽는다). 그래서 템플릿을 둔다.
# ★ DB 이름을 dev 와 절대 같게 두지 말 것 — 픽스처가 TRUNCATE 를 돌린다.
# conftest 의 안전가드가 이름을 확인하지만, 여기서부터 갈라 두는 게 먼저다.
[WebServerConfig]
server_name = "O2oSiteServerTest"
port = 9800
process_count = 1
is_ssl = false
is_test = true
client_url = "http://localhost:3000"
landing_url = ""
[LogConfig]
print_console = false
log_level = "warning"
[MainDBConfig]
db_type = "postgresql"
name = "web4ai_test_db" # ★ dev(web4ai_db)와 다른 DB. 픽스처가 매번 지웠다 만든다
write_host = "127.0.0.1"
write_port = 5432
write_id = "postgres"
write_pw = "password"
read_host = "127.0.0.1"
read_port = 5432
read_id = "postgres"
read_pw = "password"
show_log = false
pool_size = 5
max_overflow = 10
sslmode = ""
[JwtToken]
access_key = "test-access-key-not-a-secret"
refresh_key = "test-refresh-key-not-a-secret"
access_expire_min = 30
refresh_expire_day = 7
# ★ 전부 빈값으로 둔다. APP_ENV=test 는 .env 를 읽지 않는데(실키가 테스트로 새는 경로 차단),
# 여기에 실키를 적으면 그 차단을 우회해 외부 API 요금이 나간다.
[ExternalApiConfig]
perplexity_api_key = ""
kakao_rest_api_key = ""
naver_client_id = ""
naver_client_secret = ""
gemini_api_key = ""
tour_api_key = ""
+37
View File
@@ -0,0 +1,37 @@
import tomllib
from typing import Optional, Type, Dict, TypeVar
from pydantic import BaseModel
class ConfigModel(BaseModel):
pass
# APP_ENV
# local : 로컬 환경(개인 pc)
# dev : 개발환경 (사내 pc)
# prod : 서비스 환경 (클라우드 서버)
#
# 실행시 환경변수 설정
# linux : export APP_ENV=dev
# window : set APP_ENV=dev
class Configs:
ConfigType = TypeVar("ConfigType", bound=ConfigModel)
def __init__(self, file_path: str):
self._settings: Dict[Type["Configs.ConfigType"], "Configs.ConfigType"] = self._load_settings_from_toml(file_path)
def _load_settings_from_toml(self, file_path: str) -> Dict[Type[ConfigType], ConfigType]:
with open(file_path, "rb") as f:
toml_content = tomllib.load(f)
config_subclasses = ConfigModel.__subclasses__()
configs = {
config_class: config_class.model_validate(toml_content[config_class.__name__])
for config_class in config_subclasses
if config_class.__name__ in toml_content
}
return configs
def get(self, config_class: Type[ConfigType]) -> Optional[ConfigType]:
return self._settings.get(config_class)
+66
View File
@@ -0,0 +1,66 @@
from config.config_loader import ConfigModel
class WebServerConfig(ConfigModel):
server_name: str = ""
port: int = 0
process_count: int = 1
is_ssl: bool = False
is_test: bool = False
client_url: str = "" # 관리자 프론트 오리진. CORS 허용 대상
landing_url: str = "" # 랜딩(마케팅 사이트) 오리진. 빈값=미허용
class LogConfig(ConfigModel):
print_console: bool = True
log_level: str = "debug"
# DB Read/Write 분리 설정.
# 하나의 논리 DB 에 대해 write(주) / read(복제) 접속 정보를 각각 가진다.
class MainDBConfig(ConfigModel):
db_type: str = "postgresql"
name: str = ""
write_host: str = ""
write_port: int = 5432
write_id: str = ""
write_pw: str = ""
read_host: str = ""
read_port: int = 5432
read_id: str = ""
read_pw: str = ""
show_log: bool = False
# 커넥션 풀 사이징. 실제 동시 커넥션 상한 = (pool_size + max_overflow) x 엔진수(R/W=2) x 워커수.
# PostgreSQL max_connections 를 넘지 않도록 설정해야 한다. (예: 10+20=30 x 2 x 5워커 = 300)
pool_size: int = 10
max_overflow: int = 20
# SSL/TLS 모드: ""/"disable"=미사용(로컬), "require"/"verify-ca"/"verify-full"=관리형 DB(RDS/Aurora/Azure).
sslmode: str = ""
class JwtToken(ConfigModel):
access_key: str = ""
refresh_key: str = ""
access_expire_min: int = 30
refresh_expire_day: int = 7
# 외부 API 키. 수집 파이프라인(Perplexity → 카카오 로컬 → 크롤링 → Gemini)이 쓴다.
# 키가 비면 해당 어댑터는 비활성 — 서버는 그대로 뜬다(부팅이 외부 계약에 묶이면 안 된다).
class ExternalApiConfig(ConfigModel):
perplexity_api_key: str = "" # 채널 URL 발견 (api.perplexity.ai)
# 동일 업소 검증 — 두 소스 중 설정된 쪽을 쓴다(둘 다 있으면 카카오 우선).
# 카카오: 15건 · 전화번호 O · 고유 place id O · 행정구역 코드 O → 판정 근거가 강하다
# 네이버: 5건 · 전화번호 X · 고유 id 불확실 · 행정구역 코드 X → 그만큼 AMBIGUOUS 가 늘어난다
kakao_rest_api_key: str = "" # dapi.kakao.com (미발급)
naver_client_id: str = "" # openapi.naver.com 지역검색
naver_client_secret: str = ""
gemini_api_key: str = "" # 사진 분류 + 카피 작성 (Google AI Studio)
# 비전 모델. 사진 1장 ≈ 1,200 토큰이라 사업장 1건(50장)에 3.7-flash $0.045 / 2.5-flash $0.018.
# 기본을 3.7 로 두는 이유: 라벨이 틀리면 사람 확인 큐 비용이 모델 값 차이보다 크다.
gemini_vision_model: str = "gemini-3.7-flash"
# 소개문·FAQ 생성 모델. 비전과 따로 둔다 — 텍스트는 토큰이 적어 상위 모델을 써도 싸다.
gemini_text_model: str = "gemini-3.7-flash"
# ★ 이 값 미만이면 자동 반영하지 않고 사람 확인 큐(PENDING_REVIEW)에 남긴다. 운영하며 조정한다.
vision_confidence_threshold: float = 0.7
tour_api_key: str = "" # 공공데이터포털 일반 인증키(전국문화축제표준데이터)
+107
View File
@@ -0,0 +1,107 @@
import os
from dotenv import load_dotenv
from config.config_loader import Configs
from config.config_models import WebServerConfig, LogConfig, MainDBConfig, JwtToken, ExternalApiConfig
# 레포 최상위 .env 를 환경변수로 올린다 (외부 API 키·DB 접속의 배포용 주입 경로).
# override=False: 이미 설정된 실제 환경변수(docker-compose 등)가 항상 이긴다.
# 우선순위 = 실제 환경변수 > .env > config.{APP_ENV}.toml
#
# ★ APP_ENV=test 면 .env 를 읽지 않는다. 실키가 테스트 환경에 새어 들어가면
# 테스트가 실제 외부 API(Perplexity·Gemini·카카오)를 때리고 요금이 나간다.
# 테스트의 외부 연동은 config.test.toml(전 키 빈 값) + MockAdapter 로만 검증한다.
_DOTENV_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), ".env")
if os.environ.get("APP_ENV") != "test":
load_dotenv(_DOTENV_PATH, override=False)
# 실행 환경 결정 (기본 local). 환경변수 APP_ENV 로 변경.
APP_ENV = os.environ.get("APP_ENV", "local")
_config_dir = os.path.dirname(__file__)
_config_file = os.path.join(_config_dir, f"config.{APP_ENV}.toml")
# 운영 전제: 항상 APP_ENV=local 로 띄운다 → config.local.toml 사용 (test/docker 도 local 로 실행).
if not os.path.exists(_config_file):
raise FileNotFoundError(f"설정 파일이 없습니다: {_config_file} (APP_ENV={APP_ENV}). APP_ENV=local 로 실행하세요.")
configs = Configs(_config_file)
web_server_config: WebServerConfig = configs.get(WebServerConfig)
log_config: LogConfig = configs.get(LogConfig)
main_db_config: MainDBConfig = configs.get(MainDBConfig)
jwt_token_config: JwtToken = configs.get(JwtToken)
# [ExternalApiConfig] 섹션이 없는 toml 에서도 죽지 않게 기본값 폴백(전 키 빈 값 → 해당 어댑터 비활성).
external_api_config: ExternalApiConfig = configs.get(ExternalApiConfig) or ExternalApiConfig()
# DB 접속 env override (config.local.toml 유지, 도커에서 host 만 교체). 로컬은 env 미설정 → toml 그대로.
def _apply_db_env_override(cfg: MainDBConfig):
h = os.environ.get("DB_HOST")
if h:
cfg.write_host = cfg.read_host = h
if os.environ.get("DB_PORT"):
cfg.write_port = cfg.read_port = int(os.environ["DB_PORT"])
if os.environ.get("DB_USER"):
cfg.write_id = cfg.read_id = os.environ["DB_USER"]
if os.environ.get("DB_PASSWORD"):
cfg.write_pw = cfg.read_pw = os.environ["DB_PASSWORD"]
if os.environ.get("DB_NAME"):
cfg.name = os.environ["DB_NAME"]
_apply_db_env_override(main_db_config)
# 외부 API 키 env override — 키를 toml 에 안 두고 배포 환경변수로만 주입하는 경우.
def _apply_external_api_env_override(cfg: ExternalApiConfig):
if os.environ.get("PERPLEXITY_API_KEY"):
cfg.perplexity_api_key = os.environ["PERPLEXITY_API_KEY"]
if os.environ.get("KAKAO_REST_API_KEY"):
cfg.kakao_rest_api_key = os.environ["KAKAO_REST_API_KEY"]
if os.environ.get("NAVER_CLIENT_ID"):
cfg.naver_client_id = os.environ["NAVER_CLIENT_ID"]
if os.environ.get("NAVER_CLIENT_SECRET"):
cfg.naver_client_secret = os.environ["NAVER_CLIENT_SECRET"]
if os.environ.get("GEMINI_API_KEY"):
cfg.gemini_api_key = os.environ["GEMINI_API_KEY"]
if os.environ.get("GEMINI_VISION_MODEL"):
cfg.gemini_vision_model = os.environ["GEMINI_VISION_MODEL"]
if os.environ.get("GEMINI_TEXT_MODEL"):
cfg.gemini_text_model = os.environ["GEMINI_TEXT_MODEL"]
if os.environ.get("VISION_CONFIDENCE_THRESHOLD"):
cfg.vision_confidence_threshold = float(os.environ["VISION_CONFIDENCE_THRESHOLD"])
if os.environ.get("TOUR_API_KEY"):
cfg.tour_api_key = os.environ["TOUR_API_KEY"]
_apply_external_api_env_override(external_api_config)
# JWT 시크릿 env override.
# ★ 도커 이미지는 config.local.toml 을 example 사본(플레이스홀더)으로 굽는다 — 시크릿을 안 굽기 위해서다.
# 그래서 env 로 주입하지 않으면 "<JWT_ACCESS_SECRET>" 이라는 공개된 문자열이 서명 키가 된다.
# 운영에서는 반드시 env 로 넣어야 한다.
def _apply_jwt_env_override(cfg: JwtToken):
if os.environ.get("JWT_ACCESS_SECRET"):
cfg.access_key = os.environ["JWT_ACCESS_SECRET"]
if os.environ.get("JWT_REFRESH_SECRET"):
cfg.refresh_key = os.environ["JWT_REFRESH_SECRET"]
if os.environ.get("JWT_ACCESS_EXPIRE_MIN"):
cfg.access_expire_min = int(os.environ["JWT_ACCESS_EXPIRE_MIN"])
if os.environ.get("JWT_REFRESH_EXPIRE_DAY"):
cfg.refresh_expire_day = int(os.environ["JWT_REFRESH_EXPIRE_DAY"])
_apply_jwt_env_override(jwt_token_config)
# 플레이스홀더가 그대로 남아 있으면(=env 미주입 도커) 눈에 띄게 경고한다.
# 부팅은 막지 않는다 — 로컬 개발에서 토큰이 안 필요한 작업까지 못 하게 되면 곤란하다.
if jwt_token_config.access_key.startswith("<") or jwt_token_config.refresh_key.startswith("<"):
from common.logger import LOG
LOG.w(
"[보안] JWT 시크릿이 플레이스홀더입니다 — JWT_ACCESS_SECRET / JWT_REFRESH_SECRET 를 env 로 주입하세요. "
"이 상태로 운영에 띄우면 서명 키가 공개값입니다."
)