Как повторно отправить один и тот же запрос в Django api

У меня есть BuyproducTviewset, использующий createModelMixin, который создает экземпляр, когда делается пост запрос, но я хочу повторить тот же самый запрос создания снова через 5 секунд от api в зависимости от условия, если цена больше определенного диапазона.

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

если вы повторно отправите тот же запрос, это может стать причиной бесконечного цикла.

Но вы можете это сделать:

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)

Не забывайте. Этот код синхронный. time.sleep(5) блокирует другие процессы на 5 сек.

Вернуться на верх