2

I write a bot for Vkontakte on Django(2.2.4), with the vk_api library

Some of the functions are quite long (performed in 5-7 seconds). But Vkontakte requires the server to respond no longer than 3 seconds. If the response is delayed, the request is sent again, and the bot starts sending the same message many times after a while. (I Use The Callback Api)

I will describe my problem briefly

  • my function runs for more than 6 seconds

  • the 200OK response must be sent in less than 3 seconds

Is it possible to solve this problem without major changes in the code?

# views.py
@csrf_exempt
def MainBotView(request):
    # i need something like return HttpResponse('ok') here

    ... my slow code ...

    return HttpResponse('ok') # but I don't need it at the end

(I use pythonanywhere and Celery perhaps does not work there)

Should I use threading? How?

miriskrit
  • 69
  • 5
  • put your slow code in a thread , start , return and deal with thread – vks Apr 22 '20 at 20:36
  • 1
    shouldnt that be a `202 Accepted`, not a 200? – JL Peyret Apr 22 '20 at 20:36
  • 2
    Spawning threads in WSGI web applications is not safe. The WSGI server might dispose whole processes with all its threads. You should store the request and use a background processing outside of the web application. Celery is a service that could be helpful. – Klaus D. Apr 22 '20 at 20:40
  • Vkontakte requires a response with the code 200 and " OK" – miriskrit Apr 22 '20 at 20:41
  • 1
    Possible duplicate of https://stackoverflow.com/questions/51790935/django-how-to-execute-a-function-asynchronously-i-e-handover-a-task-to-a-sub-pr – MohitC Apr 22 '20 at 20:45
  • There is a help page on the PythonAnywhere help pages on how to do long-running tasks outside of the web app. Search for "async" in the help pages. – Glenn Apr 23 '20 at 09:38

0 Answers0