All checks were successful
Deploy Beta (NATIVE) / deploy (push) Successful in 37s
40 lines
1.5 KiB
Python
40 lines
1.5 KiB
Python
import requests
|
|
from django.db.models.signals import post_save, post_delete
|
|
from django.dispatch import receiver
|
|
from .models import Product
|
|
import os
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
INDEX_ENDPOINT = os.environ.get('SEARCH_INDEX_ENDPOINT', 'http://127.0.0.1:8087/api/index/product/')
|
|
|
|
@receiver(post_save, sender=Product)
|
|
def sync_product_to_search_engine(sender, instance, created, **kwargs):
|
|
try:
|
|
data = {
|
|
'id': str(instance.id),
|
|
'sku': instance.sku,
|
|
'title': instance.title,
|
|
'description': instance.description or '',
|
|
'category': instance.category,
|
|
'supplier_id': instance.supplier_id if instance.supplier_id else 0,
|
|
'price': float(instance.price),
|
|
'compare_at_price': float(instance.compare_at_price or 0.0),
|
|
'stock': instance.stock,
|
|
'image': instance.image or '',
|
|
'is_gi_tagged': instance.is_gi_tagged,
|
|
'is_active': instance.is_active,
|
|
'status': instance.status,
|
|
}
|
|
requests.post(INDEX_ENDPOINT, json=data, timeout=2.0)
|
|
except Exception as e:
|
|
logger.warning(f"Failed to sync product {instance.sku} to search engine: {e}")
|
|
|
|
@receiver(post_delete, sender=Product)
|
|
def delete_product_from_search_engine(sender, instance, **kwargs):
|
|
try:
|
|
delete_url = f"{INDEX_ENDPOINT}{instance.id}/"
|
|
requests.delete(delete_url, timeout=2.0)
|
|
except Exception as e:
|
|
logger.warning(f"Failed to delete product {instance.sku} from search engine: {e}")
|