Files
Parser_recipes/import_in_BD.py
zein 12c4dcf33b Финальная сборка.
Собраны все ссылки, удалены дубликаты. Осталось 85к ссылок. Парсим рецепты
2025-11-24 03:24:08 +03:00

70 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 в файл для повторной обработки