syncer.py 1.04 KB
from app.core.log import setup_logging

logger = setup_logging('sync_data')


def preprocess_text(text):
    if not text:
        return ""
    return str(text).strip()


def sync_merchants(conn, api_rows):
    batch_data = []
    seen_ids = set()

    for item in api_rows:
        m_id = item.get("merchantId")
        m_name = item.get("merchantName")
        if m_id and m_id not in seen_ids:
            batch_data.append((str(m_id), preprocess_text(m_name)))
            seen_ids.add(m_id)

    if not batch_data:
        logger.warning("解析后无有效商户数据,未执行写入。")
        return

    merchant_names = [item[1] for item in batch_data]
    logger.info(f"准备写入以下门店: {', '.join(merchant_names)}")

    cursor = conn.cursor()
    cursor.executemany(
        "INSERT INTO merchants (merchantNo, name) VALUES (?, ?);",
        batch_data
    )
    conn.commit()

    logger.info(
        f"同步成功!共从接口获取 {len(api_rows)} 条记录,"
        f"去重后写入 {len(batch_data)} 条商户数据。"
    )