AutoPercenty/mongo_config.py

80 lines
3.3 KiB
Python

from pymongo import MongoClient
from configparser import ConfigParser
import os, sys
import logging
# 로거 인스턴스 가져오기
logger = logging.getLogger('default_logger')
class MongoConfig:
_instance = None # 클래스 레벨의 인스턴스 변수
def __new__(cls):
if cls._instance is None:
cls._instance = super(MongoConfig, cls).__new__(cls)
cls._instance.init_config()
return cls._instance
def get_config_path(self):
if getattr(sys, 'frozen', False):
# PyInstaller가 생성한 임시 폴더에서 실행 중
application_path = sys._MEIPASS
else:
# 일반 Python 환경에서 실행 중
application_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(application_path, 'config.ini')
def init_config(self):
config_path = self.get_config_path()
self.config = ConfigParser()
self.config.read(config_path)
# config_path = os.path.join(os.path.dirname(__file__), 'config.ini')
self.config.read(config_path)
logger.debug(f"{config_path}")
self.client = None # MongoDB 클라이언트 초기화
self.load_config()
def load_config(self):
if not self.config.has_section('MongoDB'):
raise Exception('서버 설정파일이 없습니다.config.ini 파일을 체크하세요.')
if self.config.has_section('MongoDB'):
address = self.config.get('MongoDB', 'address', fallback='localhost')
port = self.config.get('MongoDB', 'port', fallback='27017')
user = self.config.get('MongoDB', 'user', fallback='')
password = self.config.get('MongoDB', 'password', fallback='')
if not all([address, port, user, password]):
raise Exception('Incomplete MongoDB configuration. Please check your config.ini file.')
return address, port, user, password
# def connect(self):
# self.client = MongoClient(f'mongodb://{self.user}:{self.password}@{self.address}:{self.port}/')
# self.db = self.client['taobao_project']
@staticmethod
def get_db():
return MongoConfig()._instance.db
def save_config(self, address, port, user, password):
self.config['MongoDB'] = {
'address': address,
'port': port,
'user': user,
'password': password
}
with open('config.ini', 'w') as configfile:
self.config.write(configfile)
def try_connect(self, address, port, user, password):
address, port, user, password = self.load_config()
# logger.debug(f"{address},{port},{user},{password}")
if not all([address, port, user, password]):
logger.debug("Configuration missing. Please check your config.ini file.")
return False
try:
self.client = MongoClient(f'mongodb://{user}:{password}@{address}:{port}/')
self.db = self.client['taobao_project'] # 여기에서 추가 연결 확인 작업을 수행할 수 있습니다.
logger.debug("MongoDB 연결 성공.")
return True
except Exception as e:
logger.debug(f"MongoDB 연결 실패: {e}", exc_info=True)
return False