Przeglądaj źródła

upload api created

Harshit Pathak 3 miesięcy temu
rodzic
commit
8cb0dfe724
3 zmienionych plików z 70 dodań i 1 usunięć
  1. 3 1
      attr_extraction/urls.py
  2. 67 0
      attr_extraction/views.py
  3. BIN
      db.sqlite3

+ 3 - 1
attr_extraction/urls.py

@@ -1,9 +1,11 @@
 # ==================== urls.py ====================
 from django.urls import path
-from .views import ExtractProductAttributesView, BatchExtractProductAttributesView, ProductListView
+from .views import ExtractProductAttributesView, BatchExtractProductAttributesView, ProductListView, ProductUploadExcelView
 
 urlpatterns = [
     path('extract/', ExtractProductAttributesView.as_view(), name='extract-attributes'),
     path('batch-extract/', BatchExtractProductAttributesView.as_view(), name='batch-extract-attributes'),
     path('products/', ProductListView.as_view(), name='batch-extract-attributes'),
+    path('products/upload-excel/', ProductUploadExcelView.as_view(), name='product-upload-excel'),
+
 ]

+ 67 - 0
attr_extraction/views.py

@@ -350,3 +350,70 @@ class ProductListView(APIView):
         serializer = ProductSerializer(products, many=True)
         return Response(serializer.data, status=status.HTTP_200_OK)
 
+
+
+
+
+
+import pandas as pd
+from rest_framework.parsers import MultiPartParser, FormParser
+from rest_framework.views import APIView
+from rest_framework.response import Response
+from rest_framework import status
+from .models import Product
+from .serializers import ProductSerializer
+
+
+class ProductUploadExcelView(APIView):
+    """
+    POST API to upload an Excel file and add data to Product model
+    """
+    parser_classes = (MultiPartParser, FormParser)
+
+    def post(self, request, *args, **kwargs):
+        file_obj = request.FILES.get('file')
+        if not file_obj:
+            return Response({'error': 'No file provided'}, status=status.HTTP_400_BAD_REQUEST)
+
+        try:
+            # Read the Excel file
+            df = pd.read_excel(file_obj)
+
+            # Normalize column names
+            df.columns = [c.strip().lower().replace(' ', '_') for c in df.columns]
+
+            # Expected columns
+            expected_cols = {
+                'item_id',
+                'product_name',
+                'product_long_description',
+                'product_short_description',
+                'product_type',
+                'image_path'
+            }
+
+            if not expected_cols.issubset(df.columns):
+                return Response({
+                    'error': 'Missing required columns',
+                    'required_columns': list(expected_cols)
+                }, status=status.HTTP_400_BAD_REQUEST)
+
+            # Loop through rows and create Product entries
+            created_count = 0
+            for _, row in df.iterrows():
+                Product.objects.create(
+                    item_id=row.get('item_id', ''),
+                    product_name=row.get('product_name', ''),
+                    product_long_description=row.get('product_long_description', ''),
+                    product_short_description=row.get('product_short_description', ''),
+                    product_type=row.get('product_type', ''),
+                    image_path=row.get('image_path', ''),
+                )
+                created_count += 1
+
+            return Response({
+                'message': f'Successfully uploaded {created_count} products.'
+            }, status=status.HTTP_201_CREATED)
+
+        except Exception as e:
+            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

BIN
db.sqlite3