환경변수 호출 및 db 조회 리팩토링

This commit is contained in:
icurfer 2024-10-03 21:26:06 +09:00
parent 4d1fd7a5be
commit 019a1419d1
5 changed files with 84 additions and 8 deletions

12
main.py
View File

@ -1,4 +1,12 @@
import package as pkg
from package import GetConfig
from package import MariaDB
# 2024-10-03 환경 변수 호출
config = GetConfig.GetConfig()
dict_data = config.get_config_as_dict()
# 2024-10-03 db에서 url정보 호출
db = MariaDB.MariaDB(dict_data)
url = db.fetch_data_from_mariadb()['url']
url = pkg.get_url.fetch_data_from_mariadb()

View File

@ -5,14 +5,24 @@ load_dotenv(r'./.env.dev')
class GetConfig:
def __init__(self):
self.host = os.getenv('DB_HOST')
self.user = os.getenv('DB_USER')
self.password = os.getenv('DB_PASSWORD')
self.database = os.getenv('DB_NAME')
self.db_host = os.getenv('DB_HOST')
self.db_user = os.getenv('DB_USER')
self.db_pw = os.getenv('DB_PASSWORD')
self.db_database = os.getenv('DB_NAME')
self.openai_api_key = os.getenv('OPEN_API_KEY')
self.wp_url = os.getenv('WP_URL')
self.wp_user = os.getenv('WP_USER')
self.wp_api_key = os.getenv('WP_API_KEY')
self.wp_post_style = os.getenv('WP_POST_STYLE')
def show_config(self):
for key, value in self.__dict__.items():
print(f"{key.upper()}: {value}")
def get_config_as_dict(self):
# 인스턴스 속성을 딕셔너리로 반환
return self.__dict__
if __name__ == "__main__":
# 결과 확인

57
package/MariaDB.py Normal file
View File

@ -0,0 +1,57 @@
import mysql.connector
import os
class MariaDB:
def __init__(self, dict):
self.db_host = dict['db_host']
self.db_user = dict['db_user']
self.db_pw = dict['db_pw']
self.db_database = dict['db_database']
def show_config(self):
for key, value in self.__dict__.items():
print(f"{key.upper()}: {value}")
def fetch_data_from_mariadb(self):
try:
# 데이터베이스 연결
connection = mysql.connector.connect(
host=self.db_host,
user=self.db_user,
password=self.db_pw,
database=self.db_database
)
# 커서 생성
cursor = connection.cursor(dictionary=True)
# 쿼리 실행
query = "SELECT * FROM healty_url_source ORDER BY idx DESC LIMIT 1;"
cursor.execute(query)
# 결과 가져오기
result = cursor.fetchone()
return result
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
if __name__ == "__main__":
import GetConfig
config = GetConfig.GetConfig()
# config 잘 가져오는지 확인
config_dict = config.get_config_as_dict()
# MariaDB 테스트
dbg = MariaDB(config_dict)
# dbg.show_config()
url = dbg.fetch_data_from_mariadb()
print(url['url'])

View File

@ -1 +1,2 @@
from . import get_url
from . import GetConfig
from . import MariaDB

View File

@ -2,7 +2,7 @@ import os
from dotenv import load_dotenv
import markdown
import package.translate_article as ta
import ../openai/open_ai as oa
import package.open_ai as oa
# .env 파일에서 API 키 로드
load_dotenv(r'./.env.dev')