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

用户1582859

慢函数(如代码注释中所见)现在对于一个微不足道的请求的总时间高达 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"
    }
  }
}
用户1582859

是这样解决的:

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

newThread.start()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章