如何在调用慢速函数时获得快速返回值?

时间:2017-07-20 20:52:05

标签: python api asynchronous

慢速功能(如代码注释中所示)现在为一个微不足道的请求重达11秒。比调用API具有的10秒时限高出一个数量级。

无法进行优化,因为其中一些API是第三方。我认为我需要的是找到一种方法来将API调用卸载到异步任务(而不是正常的顺序编程),进程或线程中,这可能发生在自己的时间。

@app.route('/webhook', methods=['POST'])
def webhook():
    # Get JSON request 
    jsonRequest = request.get_json(silent=True, force=True)

    # Call slow function and get the result
    appResult = process_request(jsonRequest)
    appResult = json.dumps(appResult, indent=4)

    # Make a JSON response 
    jsonResponse = make_response(appResult)
    jsonResponse.headers['Content-Type'] = 'application/json'

    return jsonResponse



def process_request(req):

# Call a separate function here or do it all in this one (API Calls, processing etc)

# Return a value        
    return {
  "version": "1.0",
  "response": {
    "shouldEndSession": True,
    "outputSpeech": {
      "type": "PlainText",
      "text": "Return String"
    },
    "card": {
      "type": "Simple",
      "title": "Title",
      "content": "Return String"
    }
  }
}

1 个答案:

答案 0 :(得分:0)

这是如何解决的:

newThread = threading.Thread(target=api_processing_thread, args=[jsonRequest])

newThread.start()