Skip to content

Commit 80073d9

Browse files
committed
SQLite 및 Oracle 데이터베이스에 TELEGRAM_URL 업데이트 로직 추가
1 parent 316e912 commit 80073d9

File tree

2 files changed

+61
-45
lines changed

2 files changed

+61
-45
lines changed

scrap_af_main.py

Lines changed: 41 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import json
55
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
66
from models.SQLiteManager import SQLiteManager
7+
from models.OracleManagerSQL import OracleManagerSQL
8+
79
from models.FirmInfo import FirmInfo
810
from modules.LS_0 import LS_detail
911
from modules.DBfi_19 import fetch_detailed_url
@@ -15,60 +17,67 @@ async def update_firm_telegram_url_by_date(date_str=None):
1517
firm_names 배열의 모든 인덱스를 순회하며, telegram_update_required가 True인 경우 TELEGRAM_URL 컬럼을 업데이트합니다.
1618
"""
1719
print('update_firm_telegram_url_by_date')
18-
db = SQLiteManager()
20+
sqliteDB = SQLiteManager()
21+
oracleDB = OracleManagerSQL()
1922
all_records = [] # 모든 회사의 레코드를 저장할 리스트
2023

21-
# firm_names 배열의 모든 인덱스를 순회
2224
for sec_firm_order in range(len(FirmInfo.firm_names)):
2325
firm_info = FirmInfo(sec_firm_order=sec_firm_order, article_board_order=0)
2426

25-
# 회사 이름이 공백이 아니고, telegram_update_required가 True인 경우만 처리
2627
if firm_info.get_firm_name() and firm_info.telegram_update_required:
27-
records = await db.fetch_daily_articles_by_date(firm_info=firm_info, date_str=date_str)
28-
print(f"Total records count{len(records)}")
29-
# records가 빈 리스트가 아닌 경우에만 처리 진행
28+
# === SQLite 처리 ===
29+
records = await sqliteDB.fetch_daily_articles_by_date(firm_info=firm_info, date_str=date_str)
30+
print(f"[SQLite] Total records count: {len(records)}")
3031
if records:
31-
print(f"Fetched records for SEC_FIRM_ORDER {sec_firm_order}: records count{len(records)}")
32+
print(f"[SQLite] Fetched records for SEC_FIRM_ORDER {sec_firm_order}")
3233
all_records.extend(records)
3334

34-
# 조건에 따라 추가 작업 수행
3535
if sec_firm_order == 19:
36-
# sec_firm_order가 19인 경우 업데이트 수행
37-
print("Updating TELEGRAM_URL for records with SEC_FIRM_ORDER 19")
38-
update_records = await fetch_detailed_url(records) # all_records 대신 records 사용
36+
print("Updating TELEGRAM_URL for SEC_FIRM_ORDER 19 in SQLite")
37+
update_records = await fetch_detailed_url(records)
3938
for record in update_records:
40-
await db.update_telegram_url(record['id'], record['TELEGRAM_URL'])
41-
print(f"Updated TELEGRAM_URL for id {record['id']} with {record['TELEGRAM_URL']}")
42-
39+
await sqliteDB.update_telegram_url(record['id'], record['TELEGRAM_URL'])
40+
print(f"[SQLite] Updated TELEGRAM_URL for id {record['id']}")
41+
4342
elif sec_firm_order == 0:
44-
# sec_firm_order가 0인 경우 추가 작업 수행
45-
print("Additional processing for SEC_FIRM_ORDER 0")
46-
print(f"records{len(records)}")
43+
print("Additional processing for SEC_FIRM_ORDER 0 in SQLite")
4744
for record in records:
48-
await LS_detail(articles=record, firm_info=firm_info) # all_records 대신 records 사용
49-
r = await db.update_telegram_url(record['id'], record['TELEGRAM_URL'], record['ARTICLE_TITLE'])
45+
await LS_detail(articles=record, firm_info=firm_info)
46+
r = await sqliteDB.update_telegram_url(record['id'], record['TELEGRAM_URL'], record['ARTICLE_TITLE'])
5047
print(r)
5148

52-
# update_records = LS_detail(articles=records, firm_info=firm_info) # all_records 대신 records 사용
53-
54-
# for record in update_records:
55-
# await db.update_telegram_url(record['id'], record['TELEGRAM_URL'], record['ARTICLE_TITLE'])
56-
# print(f"Updated TELEGRAM_URL for id {record['id']} with {record['TELEGRAM_URL']}")
49+
# === Oracle 처리 ===
50+
oracle_records = await oracleDB.fetch_daily_articles_by_date(firm_info=firm_info, date_str=date_str)
51+
print(f"[Oracle] Total records count: {len(oracle_records)}")
52+
if oracle_records:
53+
print(f"[Oracle] Fetched records for SEC_FIRM_ORDER {sec_firm_order}")
54+
all_records.extend(oracle_records)
55+
56+
if sec_firm_order == 19:
57+
print("Updating TELEGRAM_URL for SEC_FIRM_ORDER 19 in Oracle")
58+
update_records = await fetch_detailed_url(oracle_records)
59+
for record in update_records:
60+
await oracleDB.update_telegram_url(record['id'], record['TELEGRAM_URL'])
61+
print(f"[Oracle] Updated TELEGRAM_URL for id {record['id']}")
62+
63+
elif sec_firm_order == 0:
64+
print("Additional processing for SEC_FIRM_ORDER 0 in Oracle")
65+
for record in oracle_records:
66+
await LS_detail(articles=record, firm_info=firm_info)
67+
r = await oracleDB.update_telegram_url(record['id'], record['TELEGRAM_URL'], record['ARTICLE_TITLE'])
68+
print(r)
5769

58-
# 전체 회사들의 레코드가 JSON 리스트로 모임
59-
if all_records: # all_records가 비어 있지 않은 경우에만 JSON 변환 및 출력 수행
70+
if all_records:
6071
json_records = json.dumps(all_records, indent=2)
6172
print(f"Combined JSON Records size:\n{len(json_records)}")
6273

74+
# 메인 함수
6375
# 메인 함수
6476
async def main():
65-
# firm_info = FirmInfo(
66-
# sec_firm_order=19,
67-
# article_board_order=0
68-
# )
69-
# TELEGRAM_URL 업데이트 함수 호출
70-
print('?????????????')
77+
print('Starting TELEGRAM_URL update for all firms...')
7178
await update_firm_telegram_url_by_date()
79+
print('All updates completed.')
80+
7281

7382
if __name__ == "__main__":
7483
asyncio.run(main())

scrap_main.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
from send_error import send_message_to_shell
77

88
from models.SQLiteManager import SQLiteManager
9+
from models.OracleManagerSQL import OracleManagerSQL
10+
911
from utils.date_util import GetCurrentDate
1012

1113
# business
@@ -126,7 +128,6 @@ async def retry_db_insert_in_memory(db, data, table_name, retries=3, delay=60):
126128
# 모든 시도 실패 시
127129
print("모든 DB 삽입 시도가 실패했습니다.")
128130
return False
129-
130131
async def main():
131132
try:
132133
print('===================scrap_send===============')
@@ -179,8 +180,8 @@ async def main():
179180
print(f"Running {func.__name__}")
180181
data = func() # 동기 함수 호출
181182
if data:
182-
total_data.extend(data) # 데이터 병합
183-
totalCnt += len(data) # 카운트 증가
183+
total_data.extend(data)
184+
totalCnt += len(data)
184185
except Exception as e:
185186
logging.error(f"Error in {func.__name__}: {str(e)}", exc_info=True)
186187
send_message_to_shell(f"Error in sync function {func.__name__}: {str(e)}")
@@ -192,34 +193,41 @@ async def main():
192193
print(f"Running {func.__name__}")
193194
data = await func() # 비동기 함수 호출
194195
if data:
195-
total_data.extend(data) # 데이터 병합
196-
totalCnt += len(data) # 카운트 증가
196+
total_data.extend(data)
197+
totalCnt += len(data)
197198
except Exception as e:
198199
logging.error(f"Error in {func.__name__}: {str(e)}", exc_info=True)
199200
send_message_to_shell(f"Error in async function {func.__name__}: {str(e)}")
200201

201202
print('==============전체 레포트 제공 회사 게시글 조회 완료==============')
202203

203204
if total_data:
204-
db = SQLiteManager()
205+
sqliteDB = SQLiteManager()
206+
oracleDB = OracleManagerSQL()
205207

206-
# 데이터 삽입 시도
208+
# SQLite DB에 데이터 삽입
207209
try:
208-
inserted_count, updated_count = db.insert_json_data_list(total_data, 'data_main_daily_send')
210+
inserted_count, updated_count = sqliteDB.insert_json_data_list(total_data, 'data_main_daily_send')
209211
print(f"총 {totalCnt}개의 게시글을 스크랩하여.. DB에 Insert 시도합니다.")
210212
print(f"총 {inserted_count}개의 새로운 게시글을 DB에 삽입했고, {updated_count}개의 게시글을 업데이트했습니다.")
211213
except Exception as e:
212214
print(f"DB 삽입 중 오류 발생: {str(e)}")
213215
logging.error(f"DB Insert Error: {str(e)}", exc_info=True)
214-
215-
# 메모리에서 데이터를 보관하며 재시도
216216
print("DB 삽입 실패, 일정 시간 후 재시도합니다...")
217-
success = await retry_db_insert_in_memory(db, total_data, 'data_main_daily_send', retries=3, delay=60)
217+
success = await retry_db_insert_in_memory(sqliteDB, total_data, 'data_main_daily_send', retries=3, delay=60)
218218
if success:
219219
print("DB 재삽입 성공.")
220220
else:
221221
print("DB 재삽입 실패. 데이터를 확인하세요.")
222222

223+
# Oracle DB에 데이터 삽입
224+
try:
225+
oracle_inserted_count, oracle_updated_count = oracleDB.insert_json_data_list(total_data, 'data_main_daily_send')
226+
print(f"[Oracle] 총 {oracle_inserted_count}개의 새로운 게시글을 삽입했고, {oracle_updated_count}개의 게시글을 업데이트했습니다.")
227+
except Exception as e:
228+
print(f"[Oracle] DB 삽입 중 오류 발생: {str(e)}")
229+
logging.error(f"[Oracle] DB Insert Error: {str(e)}", exc_info=True)
230+
223231
if inserted_count or updated_count:
224232
# 추가 비동기 작업 실행
225233
await scrap_af_main.main()
@@ -228,9 +236,8 @@ async def main():
228236
else:
229237
print("새로운 게시글 스크랩 실패.")
230238
except Exception as e:
231-
# 전체 프로세스 에러 처리
232239
logging.error("An error occurred in the main process", exc_info=True)
233240
send_message_to_shell(f"Error in main: {str(e)}")
234241

235242
if __name__ == "__main__":
236-
asyncio.run(main())
243+
asyncio.run(main())

0 commit comments

Comments
 (0)