在返回http 200 OK之后执行功能



我正在处理烧瓶应用程序,该应用程序需要在2秒钟内返回HTTP 200 OK。但是我的应用在发送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

问题是响应功能需要超过2秒的时间来处理收到的数据。我需要它首先发送HTTP 200请求,然后开始其工作。

编辑

以下是响应的代码函数。

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

您需要将繁重的举重卸载到背景上,以便不必坚持响应。这通常是使用芹菜等任务队列完成的。

http://www.celeryproject.org

您也可以考虑一些轻巧的替代品,例如Huey。

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

最新更新