How to resend the same request again in Django api

90 Views Asked by At

I have a BuyproducTviewset using createModelMixin that create an instance when post request is made however I want to repeat the same create request again after 5 seconds from the api depending on a condition if the price is greater than a specific range.

class BuyProductViewset(viewsets.GenericViewSet, mixins.CreateModelMixin):
    serializer_class = UserproductSerializer
    queryset = Userproducts.objects.all()

    def data_serialize(self, user_id, product_ID):
        data = {"user": user_id, "product": product_ID}
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return serializer, headers

    def create(self, request, *args, **kwargs):

        user_id = request.data["user_id"]
        product_id = request.data["product_id"]
        total = request.data["total"]
        upper_bound = request.data["upper_bound"]
        lower_bound = request.data["lower_bound"]
        product = (
            product.objects.filter(product_id=product_id)
            .order_by("timestamp")
            .reverse()[:1]
            .values("id", "name", "price", "availability")
            .get()
        )
       
        product_ID = product["id"]
        product_price = product["price"]
        product_availability = product["availability"]
        product_name = product["name"]
        
        if product_price >= int(lower_bound) and product_price <= int(upper_bound):
     
            serializer, headers = self.data_serialize(user_id, 
            product_ID)
            product.objects.create(
                product_id=product_ID,
                name=product_name,
                price=product_price,
                availability=product_availability - int(total),
                )
            return Response(
              serializer.data, status=status.HTTP_201_CREATED, 
              headers=headers
              )
        else:
            time.sleep(5)          

            # RESEND THE SAME REQUEST WITH THE SAME DATA

        return a response
1

There are 1 best solutions below

1
Maxim Danilov On

if you resend the same request, it can be a cause for infinity loop.

But you can do it:

def create(self, request, *args, **kwargs):
    ...
    else:
        time.sleep(5)
        # RESEND THE SAME REQUEST WITH THE SAME DATA
        # here should be a reason to stop the resend process
        return self.create(request, *args, **kwargs)

Don't forget. This code is synchronous. time.sleep(5) blocks other processes for 5sec.