from pymongo import MongoClient import log_err as lg from pymongo import MongoClient, ReplaceOne def connect_to_mongo(): """Подключение к MongoDB""" client = MongoClient("mongodb://localhost:27017/") db = client["Food"] return db["Test"] def import_json_in_mongo(recipe_data): """Сохраняет один рецепт (для обратной совместимости и ошибок)""" collection = connect_to_mongo() try: collection.replace_one({"_id": recipe_data["_id"]}, recipe_data, upsert=True) print(f"✅ Рецепт '{recipe_data.get('recipe_name', recipe_data['_id'])}' успешно сохранён.") except Exception as e: print(f"❌ Ошибка при сохранении рецепта {recipe_data.get('_id')}: {e}") url = recipe_data.get('url', 'unknown') lg.log_error(url, str(e), 'Buff_err.json') def bulk_write_recipes(recipes_list): """Сохраняет список рецептов массово с помощью bulk_write""" if not recipes_list: return collection = connect_to_mongo() try: requests = [ ReplaceOne({"_id": r["_id"]}, r, upsert=True) for r in recipes_list ] result = collection.bulk_write(requests, ordered=False) print(f"✅ Bulk-запись: {len(recipes_list)} рецептов " f"(upserted: {result.upserted_count}, modified: {result.modified_count})") except Exception as e: print(f"❌ Ошибка при bulk-записи: {e}") # Опционально: можно сохранить recipes_list в файл для повторной обработки