Tencent Cloud SCF에서 Python RDB 연결 가이드
기본 설정
필요한 패키지를 먼저 설치합니다:
pip install pymysql pip install sqlalchemy
데이터베이스 연결 코드
기본 연결 설정:
import os
import pymysql
from sqlalchemy import create_engine
def get_db_connection():
host = os.environ.get('DB_HOST')
port = int(os.environ.get('DB_PORT', 3306))
user = os.environ.get('DB_USER')
password = os.environ.get('DB_PASSWORD')
database = os.environ.get('DB_NAME')
connection = pymysql.connect(
host=host,
port=port,
user=user,
password=password,
database=database,
charset='utf8mb4'
)
return connection
SQLAlchemy 사용 예제:
def get_db_engine():
DB_URL = f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"
engine = create_engine(DB_URL)
return engine
def main_handler(event, context):
try:
conn = get_db_connection()
cursor = conn.cursor()
# 쿼리 실행
cursor.execute("SELECT * FROM your_table")
result = cursor.fetchall()
# 변경사항 저장
conn.commit()
return {"statusCode": 200, "body": result}
except Exception as e:
return {"statusCode": 500, "body": str(e)}
finally:
cursor.close()
conn.close()
보안 설정
VPC 설정
- SCF 콘솔에서 VPC 설정
- 보안그룹 설정
- 데이터베이스와 동일한 VPC 선택
연결 풀링
커넥션 풀 구현:
from sqlalchemy.pool import QueuePool
engine = create_engine(
DB_URL,
poolclass=QueuePool,
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_recycle=3600
)
오류 처리
재시도 로직 구현:
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
import time
def execute_with_retry(func, max_retries=3):
for attempt in range(max_retries):
try:
return func()
except pymysql.Error as e:
if attempt == max_retries - 1:
raise e
time.sleep(2 ** attempt)
모니터링
로깅 설정:
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def log_db_operation(operation):
logger.info(f"Database operation: {operation}")
# 사용 예
log_db_operation("Connecting to database")
이러한 설정으로 Tencent Cloud SCF에서 안정적인 RDB 연결과 쿼리 실행이 가능합니다. 연결 풀링을 통해 성능을 최적화하고, 적절한 오류 처리와 모니터링을 구현하는 것이 중요합니다.