正确处理连接错误:连接中止,BadStatusLine(“'”,)

时间:2016-12-07 18:15:17

标签: python python-requests

我一直在使用Python中的requests库查询Web服务器上的数据。我收到以下错误:

ConnectionError: ('Connection aborted.', BadStatusLine("''",))

我希望我的程序中止,但测试连接并从中断处继续。我该怎么做?

我在名为query_predix_ts的函数中有以下代码,用于查询Web服务器:

r_s = requests.post(url, data=json.dumps(payload2), headers=header_store)

这是函数调用:

for tag in tags_list:
                if tag in tags_with_dim_list:
                    for dim in dims:
                        try:
                            df = query_predix_ts(t1, t2, tag, 0, this_msk, dim)
                        except(ValueError, NameError) as e:
                            print e
                        if df.shape[0] != 0:
                            sensor_type = tag + dim
                            df['sensor_type'] = sensor_type
                            # print df.head()
                            single_df.append(df)

我应该如何在try-exception中包装这一行,这样当出现连接错误时,它会继续尝试,比如5次中止?

1 个答案:

答案 0 :(得分:1)

所以你可能会在query_predix_ts方法中包含这一行,因为这是最符合逻辑的地方:

r_s = None
count = 0
while r_s is None and count < 5:
    try:
        r_s = requests.post(...)
    except requests.exceptions.ConnectionError:
        count += 1

if r_s:
    raise MyException('Could not connect to {host}'.format(...))

或者,您可以在请求中使用内置retry logic&amp; urllib3。例如,

from requests.packages.urllib3.util import retry
from requests import adapters
import requests


def query_predix_ts(...):
    session = requests.Session()
    for scheme in ('http://', 'https://'):
         session.mount(scheme, adapters.HTTPAdapter(
             max_retries=retry.Retry(connect=5),
         ))

    r_s = session.post(...)