HTTP requests.post 超时 [英] HTTP requests.post timeout

查看:37
本文介绍了HTTP requests.post 超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我下面的代码中,我使用了 requests.post.如果网站宕机,有哪些可能只是继续?

我有以下代码:

def post_test():进口请求url = 'http://example.com:8000/submit'有效载荷 = {'data1': 1, 'data2': 2}尝试:r = requests.post(url, data=payload)除了:return # 如果 requests.post 失败(例如站点关闭)我只想从 post_test() 返回.目前它挂在 requests.post 中而没有引发错误.如果(r.text == '停止'):sys.exit() # 我想终止整个程序 if r.text = 'stop' - 这很好用.

如果 example.com 或其/submit 应用程序关闭,我如何使 requests.post 超时,或从 post_test() 返回?

解决方案

使用 timeout 参数:

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

<块引用>

注意:timeout不是对整个响应下载的时间限制;相反,如果服务器没有发出响应,则会引发异常timeout 秒(更准确地说,如果在timeout 秒的底层套接字).如果没有指定超时时间明确地,请求不会超时.

In my code below, I use requests.post. What are the possibilities to simply continue if the site is down?

I have the following code:

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.

How could I make the requests.post timeout, or return from post_test() if example.com, or its /submit app is down?

解决方案

Use the timeout parameter:

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

Note: timeout is not a time limit on the entire response download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out.

这篇关于HTTP requests.post 超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆