在python中发出异步发布请求

发布时间:2020-07-07 09:08

用例:我有一个运行良好的服务器并正在运行服务请求。我需要发送一些有关我们处于哪个阶段的跟踪信息。但是,此发送的跟踪信息不应成为我的代码的阻止者。我不想等待它完成执行并继续执行我的代码库。如果以后任何时候返回错误,我都应该能够记录该错误。

使用同步调用方式的当前代码。

self.url = '/'.join([self.api_endpoint, "upload"])
body = json.dumps({"d": data})
headers_params = {'Content-Type': 'application/json;charset=utf-8'}
args = None

req = six.moves.urllib.request.Request(self.url, args, headers_params)
req.data = body.encode('utf-8')

try:
     # Open the request
     f = six.moves.urllib.request.urlopen(req)
     # Get the response
     response = f.read()
     # Close the opened request
     f.close()

except Exception as e:
     logger.exception("api exception %s" % e)
     return None

return response

理想情况下,如何将其作为异步发布请求?

回答1