-1

I am working on a Flask application which needs to return HTTP 200 OK under 2 seconds. But my app has to initiate some work after sending HTTP 200 OK.

@app.route('/events-slack', methods=['GET', 'POST'])
def events():
  if(rq.is_json):
      data = rq.get_json()
      if(data['token']==token):
          respond(data) #this function take more than 2 seconds
          r_data = {
            'OK' : True
          }
      else:
          r_data = {
            "error" : 'Token mismatch'
          }
  else:
      r_data = {
        "error" : 'Request was not JSON'
      }
  response = app.response_class(
      status=200,
      mimetype='application/json',
      response=json.dumps(r_data)
  )
  return response

The problem is respond function takes more than 2 seconds to process data it received. I need it to send an HTTP 200 request first then start it's work.

EDIT

Below is the code for respond function.

import requests
def respond(data):
    if data['type'] == "event_callback":
        event = data['event']
        if event['type'] == 'message':
            r_data = requests.post('URL', data = {'key' : 'data')
    else:
        r_data = {
                "error" : 'Type not recognized'
        }
    return r_data
Tarun Singh
  • 25
  • 2
  • 9
  • I couldn't understand anything. What is 2 seconds? Why 2 seconds? – Nabin Sep 14 '17 at 14:43
  • Well, if the problem is respond(data) takes more than 2 seconds I dont see how this code will help us to check the problem. You should show us respond's code. – lapinkoira Sep 14 '17 at 14:44
  • You could open an asynchron task before retutn response. Futher information: https://docs.python.org/3/library/asyncio-task.html – M Dennis Sep 14 '17 at 14:55
  • @Nabin I am using Slack's event API which requires a response acknowledging the request within 2 seconds, all the other processing can be done later. – Tarun Singh Sep 14 '17 at 15:18
  • @lapinkoira I added the code for respond function in the question. – Tarun Singh Sep 14 '17 at 15:25
  • Yes, you need to rethink your app flow. You should add some async task queue like celery, redis, etc – lapinkoira Sep 15 '17 at 07:18

1 Answers1

1

You need to offload the heavy lifting to the background so that you won't have to hold up the response. This is typically done using a task queue like Celery.

http://www.celeryproject.org

You can also consider some lightweight alternatives like Huey.

https://github.com/coleifer/huey/blob/master/README.rst

Ivan Choo
  • 1,997
  • 15
  • 15