Toby
Toby

Reputation: 13385

Response delay from Django REST

Possibly off topic, but having trouble researching this. I have a Django REST install, and I'd like to be able to simulate a random number of delays before responses.

My views (basically verbatim from the DRF tutorial):

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

And I'd like to be able to return between 3 and 5 failed responses before a successful response. Any guidance greatly appreciated.

Upvotes: 0

Views: 837

Answers (1)

user2390182
user2390182

Reputation: 73480

You can override the dispatch method of your view. The following would return the proper response on average for every 5th request:

import random
from django.http import Http404

class SnippetList(generics.ListCreateAPIView):
    # ...

    def dispatch(self, request, *args, **kwargs):
        if random.random() < 0.2:
            return super(SnippetList, self).dispatch(request, *args, **kwargs)
        raise Http404  # or any other custom behaviour

If you really never want to return the proper response earlier than on the n-th request, you would have to persist the number of requests since the last correct response somewhere. That somewhere could be the session (if the counting is on a per-user basis) or the database.

Upvotes: 3

Related Questions