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

2024-10-06 06:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

慢函数(如代码注释中所示)现在对于一个普通的请求来说总共需要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"
    }
  }
}

Tags: apijsontruegetreturnresponserequestdef