【问题标题】:Connection to api.openweathermap.org timed out error?连接到 api.openweathermap.org 超时错误?
【发布时间】:2018-10-27 18:30:23
【问题描述】:

我写了这段代码来获取指定城市的天气更新:

import tkinter as tk
from tkinter import *
import pyowm
from PIL import ImageTk, Image

win=tk.Tk()


#frame_for_showing_weather.
weather_frame=Frame(win,bg='black',width='300',height='300')
weather_frame.place(x=0,y=0)


weath=Label(weather_frame,font=('Agency',100),fg='white',bg='black')
weath.place(x=10,y=10)

temp1=''
owm=pyowm.OWM('a1bdf2e4609febbedaf0fcc823e3d527')

def obs():
    global temp1
    observation = owm.weather_at_place('Barisal,BD')
    w=observation.get_weather()
    temp2=w.get_temperature('celsius')
    if(temp2!=temp1):
        temp1=temp2['temp']
        weath.config(text=str(int(temp1))+chr(176))        
    weath.after(60000,obs)
obs()


win.mainloop()

但是过了一段时间,我的shell出现了这个大错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\util\connection.py", line 79, in create_connection
    raise err
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\util\connection.py", line 69, in create_connection
    sock.connect(sa)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\connectionpool.py", line 354, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Program Files (x86)\Python35-32\lib\http\client.py", line 1106, in request
    self._send_request(method, url, body, headers)
  File "C:\Program Files (x86)\Python35-32\lib\http\client.py", line 1151, in _send_request
    self.endheaders(body)
  File "C:\Program Files (x86)\Python35-32\lib\http\client.py", line 1102, in endheaders
    self._send_output(message_body)
  File "C:\Program Files (x86)\Python35-32\lib\http\client.py", line 934, in _send_output
    self.send(msg)
  File "C:\Program Files (x86)\Python35-32\lib\http\client.py", line 877, in send
    self.connect()
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\connection.py", line 196, in connect
    conn = self._new_conn()
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\connection.py", line 176, in _new_conn
    (self.host, self.timeout))
urllib3.exceptions.ConnectTimeoutError: (<urllib3.connection.HTTPConnection object at 0x041A0CB0>, 'Connection to api.openweathermap.org timed out. (connect timeout=2)')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\requests\adapters.py", line 445, in send
    timeout=timeout
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\urllib3\util\retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='api.openweathermap.org', port=80): Max retries exceeded with url: /data/2.5/weather?APPID=a1bdf2e4609febbedaf0fcc823e3d527&lang=en&q=Barisal%2CBD (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x041A0CB0>, 'Connection to api.openweathermap.org timed out. (connect timeout=2)'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\pyowm\commons\http_client.py", line 24, in get_json
    timeout=self.timeout, verify=self.verify_ssl_certs)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\requests\api.py", line 72, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\requests\sessions.py", line 512, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\requests\sessions.py", line 622, in send
    r = adapter.send(request, **kwargs)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\requests\adapters.py", line 501, in send
    raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='api.openweathermap.org', port=80): Max retries exceeded with url: /data/2.5/weather?APPID=a1bdf2e4609febbedaf0fcc823e3d527&lang=en&q=Barisal%2CBD (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x041A0CB0>, 'Connection to api.openweathermap.org timed out. (connect timeout=2)'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
  File "C:\Program Files (x86)\Python35-32\lib\tkinter\__init__.py", line 596, in callit
    func(*args)
  File "C:\Users\James Bond\Desktop\test.py", line 23, in obs
    observation = owm.weather_at_place('Barisal,BD')
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\pyowm\webapi25\owm25.py", line 210, in weather_at_place
    _, json_data = self._wapi.cacheable_get_json(uri, params=params)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\pyowm\commons\http_client.py", line 44, in cacheable_get_json
    status_code, data = self.get_json(uri, params=params, headers=headers)
  File "C:\Program Files (x86)\Python35-32\lib\site-packages\pyowm\commons\http_client.py", line 28, in get_json
    raise api_call_error.APIInvalidSSLCertificateError(str(e))
pyowm.exceptions.api_call_error.APIInvalidSSLCertificateError: Exception in calling OWM web API.

Reason: HTTPConnectionPool(host='api.openweathermap.org', port=80): Max retries exceeded with url: /data/2.5/weather?APPID=a1bdf2e4609febbedaf0fcc823e3d527&lang=en&q=Barisal%2CBD (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x041A0CB0>, 'Connection to api.openweathermap.org timed out. (connect timeout=2)'))

Caused by: None

请有人告诉我为什么会出现这个错误以及如何解决它!

【问题讨论】:

  • 超时错误总是发生在套接字和互联网上。您应该在这些调用周围使用 try..except 并学习报告这些异常并从这些异常中恢复。另外,owm=pyowm.OWM('a1bdf2e4609febbedaf0fcc823e3d527') 这一行是否有 openweathermap.org 的个人密钥?你不应该在问题中发布你的密钥,除非你这样做没有暴露。
  • 我是 python 新手。我将此代码用于我的大学项目。请给我建议我如何使用 try,除了这个错误的调用。@RufusVS
  • 重新阅读您的帖子后,不清楚它是否开始工作,但随后超时,或者它是否甚至没有获得第一次更新。您可以尝试在 Python shell 中逐行运行代码,以确保每一行都返回您所期望的。
  • @RufusVS 它开始工作,并在 1 分钟后得到更新。但是如果网络断开或网络速度慢,这个大错误发生了。我想如果我的电脑网络重新连接,这将自动开始工作

标签: python api openweathermap


【解决方案1】:

如果您想简单地忽略套接字超时,您也许可以 重写您的 obs 函数以捕获该异常,如下所示:

from socket import timeout

def obs():
    global temp1
    try:
        observation = owm.weather_at_place('Barisal,BD')
        w=observation.get_weather()
        temp2=w.get_temperature('celsius')
        if(temp2!=temp1):
            temp1=temp2['temp']
            weath.config(text=str(int(temp1))+chr(176))
    except timeout as e:
        print "socket timeout."
        pass
    weath.after(60000,obs)

这可能就是你所需要的。

我不知道 OWM 是如何工作的,您可能必须关闭它并重新打开它才能获得新的套接字。您可以在 except 块中执行此操作。添加

global owm

在您的函数和 except 块中,重复以下行:

owm=pyowm.OWM('a1bdf2e4609febbedaf0fcc823e3d527')

这将创建一个新的 OWM 对象,大概是关闭旧的并打开新的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2013-03-30
    • 2017-07-12
    相关资源
    最近更新 更多