使用线程时处理请求异常?

时间:2019-11-04 04:57:27

标签: python python-3.x

我正在线程中使用request.post,因为我已经点击了网址,而不是等待响应,因为我一次有大约4.5 k个事件被发送一次。

def request_task(url, data, headers):
    try:
        response = requests.post(url, json=data, headers=headers)

    except requests.ConnectionError as e:
        print (e)
     except requests.exceptions.RequestException as e:
         print (e)

def fire_and_forget(url, json, headers):
    x=threading.Thread(target=request_task, args=(url, json, headers))
    x.start()

def push():
    fire_and_forget(url, json=data, headers=headers)

我不确定我应该在哪里使用try块,并且我在使用线程时是否以正确的方式进行操作。

有人能建议我如何在考虑线程的情况下捕获异常

1 个答案:

答案 0 :(得分:0)

在使用request.post时,我们可以使用

def request_task(url, data, headers):
try:
    r = requests.post(url, json=data, headers=headers)
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print (e.response.text)

捕获异常。