Ошибка подключения к файлу api.openweathermap.org? - PullRequest
0 голосов
/ 27 октября 2018

Я написал этот код, чтобы получать обновления погоды в указанном городе:

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

пожалуйста, кто-нибудь подскажите, почему произошла эта ошибка и как ее можно исправить!

1 Ответ

0 голосов
/ 01 ноября 2018

Если вы хотите просто игнорировать время ожидания сокета, вы можете переписать функцию 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, возможно, вам придется закрыть его и снова открыть, чтобы получить свежий сокет.Вы можете сделать это в блоке кроме.Добавьте

global owm

в вашу функцию и в блоке исключений повторите строку:

owm=pyowm.OWM('a1bdf2e4609febbedaf0fcc823e3d527')

, которая создаст новый объект OWM, предположительно закрывая старый и открывая новыйодин.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...