我有一个简单的 Python Bottle API,用于支持 iOS 应用程序。它托管在 Heroku 上。
我使用 TelemetryDeck 进行分析,因此我想通过每个 API 调用发送信号。我没有使用 Node,所以无法使用他们的 JS SDK,因此我必须通过 HTTP 发送信号。
这是我发送遥测信号的函数。
def send_telemetry(type, success):
url = TELEMETRY_DECK_URL
headers = {
"Content-Type": "application/json; charset=utf-8"
}
data = [
{
"isTestMode": "false",
"appID": TELEMETRY_DECK_APP_ID,
"clientUser": "apiProcess",
"sessionID": "",
"type": "API Called",
"payload": {
"api_type": type,
"api_success": success
}
}
]
response = requests.post(url, headers=headers, json=data)
# Print to Heroku logs
print(response.text)
这是我从应用程序路由调用遥测方法的示例。
@app.get('/')
def example():
# Other code
if result:
send_telemetry("type", "true")
response.status = 200
return make_response(result)
else:
send_telemetry("type", "false")
response.status = 404
return make_error("Error (404)")
这一切都工作正常,但我担心遥测方法在 Bottle 返回响应之前同步运行,当然由于 WSGI 限制,它无法在响应返回后运行。
是否有一种方法可以异步触发分析方法,并且不会延迟路由中调用点的执行,因此性能不受影响。我很高兴有一个“即发即忘”的解决方案,并且不需要收到回电。
我使用
multithreading
查看了解决方案,但它们看起来比我需要的更复杂。
我实际上只是使用
threading
模块就可以完成这项工作。
在我的路由处理程序中,我只需插入此代码即可生成一个针对我的
send_telemetry
函数的线程。它按预期在单独的线程中运行,并且不会阻止 Bottle 返回响应的执行。
import threading
thread = threading.Thread(target=send_telemetry, args=["type", "true"])
thread.start()