簡體   English   中英

HTTP requests.post超時

[英]HTTP requests.post timeout

在下面的代碼中,我使用requests.post 如果網站停機,有什么可能繼續下去?

我有以下代碼:

def post_test():

    import requests

    url = 'http://example.com:8000/submit'
    payload = {'data1': 1, 'data2': 2}
    try:
        r = requests.post(url, data=payload)
    except:
        return   # if the requests.post fails (eg. the site is down) I want simly to return from the post_test(). Currenly it hangs up in the requests.post without raising an error.
    if (r.text == 'stop'):
        sys.exit()  # I want to terminate the whole program if r.text = 'stop' - this works fine.

如果exam​​ple.com或其/ submit應用程序關閉,我如何才能生成requests.post超時或從post_test()返回?

使用timeout參數:

r = requests.post(url, data=payload, timeout=1.5)

注意: timeout不是整個響應下載的時間限制; 相反,如果服務器沒有發出timeout秒的響應(更准確地說,如果在底層套接字上沒有收到timeout秒的字節),則會引發異常。 如果未明確指定超時,則請求不會超時。

所有請求都使用timeout關鍵字參數。 1

requests.post簡化了將其參數轉發到requests.request 2

當應用程序關閉時, ConnectionError可能比Timeout 3

try:
    requests.post(url, data=payload, timeout=5)
except requests.Timeout:
    # back off and retry
    pass
except requests.ConnectionError:
    pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM