【问题标题】:Dealing with HTTP IncompleteRead Error in Python在 Python 中处理 HTTP IncompleteRead 错误
【发布时间】:2015-09-12 10:05:18
【问题描述】:

我试图了解如何在下面的代码中处理http.client.IncompleteRead Error。我使用this post 中的想法处理错误。基本上,我认为这可能只是服务器限制了我可以访问数据的次数,但奇怪的是,我有时会收到 200 的 HTTP 状态代码,但下面的代码仍然返回 None 类型。这是因为出现错误时zipdata = e.partial 没有返回任何内容吗?

def update(self, ABBRV):
    if self.ABBRV == 'cd':
        try:

            my_url = 'http://www.bankofcanada.ca/stats/results/csv'
            data = urllib.parse.urlencode({"lookupPage": "lookup_yield_curve.php",
                                 "startRange": "1986-01-01",
                                 "searchRange": "all"})

            binary_data = data.encode('utf-8')
            req = urllib.request.Request(my_url, binary_data)
            result = urllib.request.urlopen(req)
            print('status:: {},{}'.format(result.status, my_url))
            zipdata = result.read()
            zipfile = ZipFile(BytesIO(zipdata))

            df = pd.read_csv(zipfile.open(zipfile.namelist()[0]))
            df = pd.melt(df, id_vars=['Date'])

            return df

        #In case of http.client.IncompleteRead Error
        except http.client.IncompleteRead as e:
            zipdata = e.partial

谢谢

【问题讨论】:

  • 你能添加你的import语句吗? (例如from zipfile import ZipFile)当我不得不花 5 分钟来计算提问者正在使用的库以便我可以运行代码并帮助他们时,这是我的主要烦恼。

标签: python pandas exception-handling


【解决方案1】:

嗯...我已经运行了您的代码 20 次而没有出现读取不完整的错误,您为什么不在读取不完整的情况下重试呢?或者另一方面,如果您的 IP 被阻止,那么他们不会向您返回任何东西是有道理的。您的代码可能如下所示:

maxretries = 3
attempt = 0
while attempt < maxretries:
   try:
      #http access code goes in here
   except http.client.IncompleteRead:
      attempt += 1
   else:
      break

【讨论】:

  • 很奇怪。它只是有时会弹出错误。以前的代码很好。另外,您的意思是将其添加到代码中:#In case of http.client.IncompleteRead Error except http.client.IncompleteRead as e: df = self.update(ABBRV)[1] return df
  • 添加了else 以确保循环终止。我知道这个问题很老,但它帮助了我,我想回馈
猜你喜欢
  • 2013-01-04
  • 2012-08-09
  • 2016-11-25
  • 2014-04-27
  • 1970-01-01
  • 2016-09-29
  • 2016-08-06
  • 2014-06-22
  • 1970-01-01
相关资源
最近更新 更多