fetcher.py 1.66 KB
import pymysql

from app.core.log import setup_logging
from app.core.config import get_config

logger = setup_logging('sync_brand')


def fetch_brands_from_mysql(host, port, user, password, database, charset="utf8mb4"):
    """
    从 MySQL cyb_os.platform_carbrand 表获取可用的品牌分组数据。

    查询条件:is_used = 0 AND parent_id = -2

    返回 list[dict],每个 dict 包含 bid 和 brand 字段。
    连接失败时返回空列表。
    """
    config = get_config()
    connect_timeout = config.getint("mysql", "connect_timeout", fallback=30)

    logger.info("正在从 MySQL 获取品牌数据...")
    logger.info(f"MySQL 连接信息: host={host}, port={port}, user={user}, database={database}")

    try:
        connection = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database,
            charset=charset,
            connect_timeout=connect_timeout,
            cursorclass=pymysql.cursors.DictCursor,
        )

        with connection.cursor() as cursor:
            sql = "SELECT bid, brand FROM cyb_os.platform_carbrand WHERE is_used = 0 AND parent_id = -2"
            cursor.execute(sql)
            rows = cursor.fetchall()

        connection.close()

        if not rows:
            logger.info("MySQL 查询结果为空,未获取到品牌数据。")
            return []

        result = [{"bid": row["bid"], "brand": row["brand"]} for row in rows]
        logger.info(f"从 MySQL 获取到 {len(result)} 条品牌数据。")
        return result

    except Exception as e:
        logger.error(f"MySQL 连接或查询失败: {e}")
        return []