Spaces:
Sleeping
Sleeping
Create db_connector.py
Browse files- db_connector.py +126 -0
db_connector.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MySQL 데이터베이스 연결 및 습득물 데이터 조회 모듈
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
import logging
|
| 6 |
+
import traceback
|
| 7 |
+
import pymysql
|
| 8 |
+
from pymysql.cursors import DictCursor
|
| 9 |
+
from contextlib import contextmanager
|
| 10 |
+
|
| 11 |
+
# 로깅 설정
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
# 데이터베이스 연결 설정
|
| 16 |
+
DB_CONFIG = {
|
| 17 |
+
'host': os.getenv('DB_HOST', 'localhost'),
|
| 18 |
+
'port': int(os.getenv('DB_PORT', 3306)),
|
| 19 |
+
'user': os.getenv('DB_USER', 'username'),
|
| 20 |
+
'password': os.getenv('DB_PASSWORD', 'password'),
|
| 21 |
+
'db': os.getenv('DB_NAME', 'foundlost'),
|
| 22 |
+
'charset': 'utf8mb4',
|
| 23 |
+
'cursorclass': DictCursor
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
@contextmanager
|
| 27 |
+
def get_db_connection():
|
| 28 |
+
"""
|
| 29 |
+
데이터베이스 연결을 제공하는 컨텍스트 매니저
|
| 30 |
+
|
| 31 |
+
Yields:
|
| 32 |
+
pymysql.connections.Connection: 데이터베이스 연결 객체
|
| 33 |
+
"""
|
| 34 |
+
connection = None
|
| 35 |
+
try:
|
| 36 |
+
connection = pymysql.connect(**DB_CONFIG)
|
| 37 |
+
logger.info("데이터베이스 연결 성공")
|
| 38 |
+
yield connection
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"데이터베이스 연결 오류: {str(e)}")
|
| 41 |
+
logger.error(traceback.format_exc())
|
| 42 |
+
raise
|
| 43 |
+
finally:
|
| 44 |
+
if connection:
|
| 45 |
+
connection.close()
|
| 46 |
+
logger.debug("데이터베이스 연결 종료")
|
| 47 |
+
|
| 48 |
+
async def fetch_found_items(limit=100, offset=0):
|
| 49 |
+
"""
|
| 50 |
+
MySQL 데이터베이스에서 습득물 데이터를 조회
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
limit (int): 조회할 최대 항목 수 (기본값: 100)
|
| 54 |
+
offset (int): 조회 시작 위치 (기본값: 0)
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
list: 습득물 데이터 목록
|
| 58 |
+
"""
|
| 59 |
+
found_items = []
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
with get_db_connection() as connection:
|
| 63 |
+
with connection.cursor() as cursor:
|
| 64 |
+
# 습득물 데이터 조회 쿼리
|
| 65 |
+
# 주요 필드: id, item_category_id, title, color, content, location, image 등
|
| 66 |
+
query = """
|
| 67 |
+
SELECT f.id, f.user_id, f.item_category_id, f.title, f.color,
|
| 68 |
+
f.content, f.location, f.image, f.status, f.lost_at, f.created_at,
|
| 69 |
+
ic.name as category_name
|
| 70 |
+
FROM found_item f
|
| 71 |
+
LEFT JOIN item_category ic ON f.item_category_id = ic.id
|
| 72 |
+
WHERE f.status = 'ACTIVE'
|
| 73 |
+
ORDER BY f.created_at DESC
|
| 74 |
+
LIMIT %s OFFSET %s
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
cursor.execute(query, (limit, offset))
|
| 78 |
+
rows = cursor.fetchall()
|
| 79 |
+
|
| 80 |
+
# 조회 결과를 API 응답 형식에 맞게 변환
|
| 81 |
+
for row in rows:
|
| 82 |
+
found_item = {
|
| 83 |
+
"id": row["id"],
|
| 84 |
+
"user_id": row["user_id"],
|
| 85 |
+
"item_category_id": row["item_category_id"],
|
| 86 |
+
"title": row["title"],
|
| 87 |
+
"color": row["color"],
|
| 88 |
+
"content": row["content"],
|
| 89 |
+
"location": row["location"],
|
| 90 |
+
"image": row["image"],
|
| 91 |
+
"status": row["status"],
|
| 92 |
+
"lost_at": row["lost_at"],
|
| 93 |
+
"category": row["category_name"] # 카테고리명 추가
|
| 94 |
+
}
|
| 95 |
+
found_items.append(found_item)
|
| 96 |
+
|
| 97 |
+
logger.info(f"{len(found_items)}개의 습득물 데이터 조회 완료")
|
| 98 |
+
|
| 99 |
+
except Exception as e:
|
| 100 |
+
logger.error(f"습득물 데이터 조회 중 오류 발생: {str(e)}")
|
| 101 |
+
logger.error(traceback.format_exc())
|
| 102 |
+
|
| 103 |
+
return found_items
|
| 104 |
+
|
| 105 |
+
# 습득물 데이터 개수 조회 함수
|
| 106 |
+
async def count_found_items():
|
| 107 |
+
"""
|
| 108 |
+
MySQL 데이터베이스에서 습득물 데이터의 총 개수를 조회
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
int: 습득물 데이터 총 개수
|
| 112 |
+
"""
|
| 113 |
+
try:
|
| 114 |
+
with get_db_connection() as connection:
|
| 115 |
+
with connection.cursor() as cursor:
|
| 116 |
+
query = "SELECT COUNT(*) as total FROM found_item WHERE status = 'ACTIVE'"
|
| 117 |
+
cursor.execute(query)
|
| 118 |
+
result = cursor.fetchone()
|
| 119 |
+
total_count = result["total"]
|
| 120 |
+
logger.info(f"총 습득물 데이터 개수: {total_count}")
|
| 121 |
+
return total_count
|
| 122 |
+
|
| 123 |
+
except Exception as e:
|
| 124 |
+
logger.error(f"습득물 데이터 개수 조회 중 오류 발생: {str(e)}")
|
| 125 |
+
logger.error(traceback.format_exc())
|
| 126 |
+
return 0
|