连接api.openweathermap.org超时错误



我写这段代码是为了获得指定城市的天气更新:

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()

但过了一段时间,我的外壳出现了一个大错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:Program Files (x86)Python35-32libsite-packagesurllib3connection.py", line 171, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "C:Program Files (x86)Python35-32libsite-packagesurllib3utilconnection.py", line 79, in create_connection
raise err
File "C:Program Files (x86)Python35-32libsite-packagesurllib3utilconnection.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-32libsite-packagesurllib3connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:Program Files (x86)Python35-32libsite-packagesurllib3connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:Program Files (x86)Python35-32libhttpclient.py", line 1106, in request
self._send_request(method, url, body, headers)
File "C:Program Files (x86)Python35-32libhttpclient.py", line 1151, in _send_request
self.endheaders(body)
File "C:Program Files (x86)Python35-32libhttpclient.py", line 1102, in endheaders
self._send_output(message_body)
File "C:Program Files (x86)Python35-32libhttpclient.py", line 934, in _send_output
self.send(msg)
File "C:Program Files (x86)Python35-32libhttpclient.py", line 877, in send
self.connect()
File "C:Program Files (x86)Python35-32libsite-packagesurllib3connection.py", line 196, in connect
conn = self._new_conn()
File "C:Program Files (x86)Python35-32libsite-packagesurllib3connection.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-32libsite-packagesrequestsadapters.py", line 445, in send
timeout=timeout
File "C:Program Files (x86)Python35-32libsite-packagesurllib3connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:Program Files (x86)Python35-32libsite-packagesurllib3utilretry.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-32libsite-packagespyowmcommonshttp_client.py", line 24, in get_json
timeout=self.timeout, verify=self.verify_ssl_certs)
File "C:Program Files (x86)Python35-32libsite-packagesrequestsapi.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "C:Program Files (x86)Python35-32libsite-packagesrequestsapi.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "C:Program Files (x86)Python35-32libsite-packagesrequestssessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "C:Program Files (x86)Python35-32libsite-packagesrequestssessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "C:Program Files (x86)Python35-32libsite-packagesrequestsadapters.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-32libtkinter__init__.py", line 1550, in __call__
return self.func(*args)
File "C:Program Files (x86)Python35-32libtkinter__init__.py", line 596, in callit
func(*args)
File "C:UsersJames BondDesktoptest.py", line 23, in obs
observation = owm.weather_at_place('Barisal,BD')
File "C:Program Files (x86)Python35-32libsite-packagespyowmwebapi25owm25.py", line 210, in weather_at_place
_, json_data = self._wapi.cacheable_get_json(uri, params=params)
File "C:Program Files (x86)Python35-32libsite-packagespyowmcommonshttp_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-32libsite-packagespyowmcommonshttp_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

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

如果您想简单地忽略套接字超时,您可以重写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对象,可能会关闭旧对象并打开新对象。

最新更新