Запись данных в MySQL

Всем привет! Я занимаюсь выгрузкой данных из 1С, передачей их на другой сервер с последующей записью в базу данных MySQL.

Появилась проблема - при выгрузке данные не записываются в БД

Вот такой JSON я получаю от 1С

{
    "timestamp": "2024-10-02T14:25:00.908023",
    "data": {
        "categories": [
            {
                "category_id": "6709dac1-80bd-11ef-bb7f-d24d0c97e2eb",
                "name": "Тестовая категория",
                "description": "олырваолпрывлдоапрдлвыарп",
                "url": "Фулл Урл",
                "name_singular": "Тестовая категория",
                "name_genitive": "Тестоуюя категория",
                "SEO": true,
                "SEO_title": "фыв",
                "SEO_description": "ыва",
                "SEO_h1": "вап",
                "SEO_keywords": "СЕО СЛОВА",
                "reflect_site": true,
                "show_header": true,
                "show_two_header": true,
                "name_Yandex": 83,
                "name_Google": 124,
                "name_Avito": 9,
                "delivery_boxberry": true,
                "Icon": "вап",
                "name_short": "Краткое описание",
                "parentTree": {
                    "parentTree_id": "",
                    "parentTree_name": ""
                },
                "image": "",
                "depth": 3,
                "width": 1,
                "height": 2
            }
        ],
        "manufacturers": [],
        "products": []
    }
}

И данные в БД не записываются

А если отправить данные не из 1С, я просто со стороннего сервера, например:

data = {
    "timestamp": "2024-10-02T13:14:32.668623",
    "data": {
        "categories": [
            {
                "category_id": "6709dac1-80bd-11ef-bb7f-d24d0c97e2eb",
                "name": "Тестовая категория",
                "description": "олырваолпрывлдоапрдлвыарп",
                "url": "Фулл Урл",
                "name_singular": "Тестовая категория",
                "name_genitive": "Тестоуюя категория",
                "SEO": True,
                "SEO_title": "фыв",
                "SEO_description": "ыва",
                "SEO_h1": "вап",
                "SEO_keywords": "апр",
                "reflect_site": True,
                "show_header": True,
                "show_two_header": True,
                "name_Yandex": 83,
                "name_Google": 124,
                "name_Avito": 2,
                "delivery_boxberry": True,
                "Icon": "вап",
                "name_short": "Краткое описание",
                "parentTree": {
                    "parentTree_id": "",
                    "parentTree_name": ""
                },
                "image": "",
                "depth": 3,
                "width": 1,
                "height": 2
            }
        ],
        "manufacturers": [],
        "products": []
    }
}

import requests
requests.post(url='http://149.154.69.188:3380/api/v1/products', json=data)

То все работает нормально и данные в БД добавляются

Вот такой скрипт обработки запросов

@app.post("/api/v1/products")
async def receive_products(request: Request):
    try:
        data = await request.json()

        products_data = data.get("data", {})

        # Логирование запроса
        log_request(data, "products_log.json")

        # Получаем соединение из пула
        connection = db_pool.get_connection()
        cursor = connection.cursor(dictionary=True)

        # Обработка категорий
        for category in products_data.get('categories', []):
            # Преобразование parent_id, если оно пустое или отсутствует
            parent_id = None
            if category.get('parentTree') and category['parentTree'].get('parentTree_id'):
                parent_id = category['parentTree']['parentTree_id']

            # Преобразование строк в целые числа для полей name_Yandex, name_Google, name_Avito
            name_yandex = category.get('name_Yandex')
            name_google = category.get('name_Google')
            name_avito = category.get('name_Avito')

            # Приведение булевых значений
            seo = bool(category.get('SEO', False))
            reflect_site = bool(category.get('reflect_site', False))
            show_header = bool(category.get('show_header', False))
            show_two_header = bool(category.get('show_two_header', False))
            delivery_boxberry = bool(category.get('delivery_boxberry', False))

            # Формирование данных для вставки/обновления категории
            category_data = {
                'id_c': str(category.get('category_id')),
                'name': str(category.get('name')),
                'description': str(category.get('description')),
                'slug': slugify(str(category.get('name'))),  # Создаем slug
                'full_slug': f"/{slugify(category.get('name'))}/",  # Генерация полного пути
                'name_nominative_case': str(category.get('name_singular')),
                'name_genitive': str(category.get('name_genitive')),
                'description_seo': str(category.get('SEO_description')),
                'seo': seo,
                'seo_title': str(category.get('SEO_title')),
                'seo_keywords': str(category.get('SEO_keywords')),
                'seo_h1': str(category.get('SEO_h1')),
                'image': str(category.get('image', '')),
                'display_on_the_site': reflect_site,
                'show_in_top_menu': show_header,
                'show_in_second_top_menu': show_two_header,
                'delivery_boxberry': delivery_boxberry,
                'boxberry_width': float(category.get('width', 0)),
                'boxberry_height': float(category.get('height', 0)),
                'boxberry_depth': float(category.get('depth', 0)),
                'icon': str(category.get('Icon', '')),
                'short_name': str(category.get('name_short', '')),
                'parent_id': parent_id,
                'name_avito_id': name_avito,
                'name_google_id': name_google,
                'name_yandex_id': name_yandex
            }

            # Вставка или обновление категории
            insert_or_update_category(category_data)

        connection.commit()

        # Закрытие соединения
        cursor.close()
        connection.close()

        return JSONResponse(status_code=200, content={"status": "success", "message": "Products processed successfully"})

    except Exception as e:
        log_request({"error": str(e)}, "general_errors_log.json")
        return JSONResponse(status_code=500, content={"status": "error", "message": "Internal Server Error"})

def insert_or_update_category(category_data):
    try:
        # Подключение к БД
        connection = db_pool.get_connection()
        cursor = connection.cursor(dictionary=True)

        # Запрос на вставку или обновление
        insert_query = """
            INSERT INTO catalog_category 
                (id_c, name, description, slug, full_slug, name_nominative_case, name_genitive, description_seo, seo, 
                 seo_title, seo_keywords, seo_h1, image, display_on_the_site, show_in_top_menu, show_in_second_top_menu, 
                 delivery_boxberry, boxberry_width, boxberry_height, boxberry_depth, icon, short_name, parent_id, 
                 name_avito_id, name_google_id, name_yandex_id)
            VALUES 
                (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE 
                name = VALUES(name),
                description = VALUES(description),
                slug = VALUES(slug),
                full_slug = VALUES(full_slug),
                name_nominative_case = VALUES(name_nominative_case),
                name_genitive = VALUES(name_genitive),
                description_seo = VALUES(description_seo),
                seo = VALUES(seo),
                seo_title = VALUES(seo_title),
                seo_keywords = VALUES(seo_keywords),
                seo_h1 = VALUES(seo_h1),
                image = VALUES(image),
                display_on_the_site = VALUES(display_on_the_site),
                show_in_top_menu = VALUES(show_in_top_menu),
                show_in_second_top_menu = VALUES(show_in_second_top_menu),
                delivery_boxberry = VALUES(delivery_boxberry),
                boxberry_width = VALUES(boxberry_width),
                boxberry_height = VALUES(boxberry_height),
                boxberry_depth = VALUES(boxberry_depth),
                icon = VALUES(icon),
                short_name = VALUES(short_name),
                parent_id = VALUES(parent_id),
                name_avito_id = VALUES(name_avito_id),
                name_google_id = VALUES(name_google_id),
                name_yandex_id = VALUES(name_yandex_id);
        """
        
        cursor.execute(insert_query, tuple(category_data.values()))
        connection.commit()
        
        cursor.close()
        connection.close()

    except mysql.connector.Error as err:
        log_request({"error": str(err)}, "error_log.json")

Ответы (0 шт):