0

I want to set a timeout in the view, if the code execution in the view exceeds the timeout

# urls.py
url(r'^test-api/$', test_api_view)

# views.py
from rest_framework import status
from rest_framework.response import Response

def test_api_view(request):
       timeout=10
      data = someMethod() 
   if xxx: # Call some_method() for more than 10 seconds, and the method call may not end   
        return Response({"error": "Timeout"})
    else:
        return Response(data)
Scheinin
  • 195
  • 9
  • Several options here: https://stackoverflow.com/questions/492519/timeout-on-a-function-call – FMc Aug 13 '20 at 04:32

1 Answers1

0

I would recommend using celery. You can find a working example here.

idea:

# views.py
from rest_framework import status
from rest_framework.response import Response
from celery.exceptions import SoftTimeLimitExceeded

from my_functions import my_function

def test_api_view(request):
    try:
        data = my_function()
    except SoftTimeLimitExceeded:
        return Response({"error": "Timeout"})
    else:
        return Response(data)
@celery.task(time_limit=20)
def mytask():
    some_method()  # method to do thing
Algebra8
  • 1,115
  • 1
  • 10
  • 23