From b4a8e0963c0309d2a4cdb76a4d7f0fd1359383da Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Thu, 9 Jun 2016 04:08:19 +0300 Subject: track_status.py: ignore connection errors This closes (hopefully) #1. --- api.py | 34 +++++++++++++++++++++++----------- track_status.py | 5 ++++- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/api.py b/api.py index 4b337ff..40df08a 100644 --- a/api.py +++ b/api.py @@ -7,6 +7,7 @@ from datetime import datetime from enum import Enum import json import sys +from urllib.error import URLError import urllib.request class Language(Enum): @@ -74,6 +75,20 @@ class User: def __str__(self): return self.value + +class Error(RuntimeError): + pass + +class InvalidResponseError(Error): + def __init__(self, response): + self.response = response + + def __str__(self): + return str(self.response) + +class ConnectionError(Error): + pass + class API: def __init__(self, lang=Language.DEFAULT): self.lang = lang @@ -95,10 +110,14 @@ class API: def _call_method(self, method, **kwargs): url = self._build_method_url(method, **kwargs) - response = json.loads(urllib.request.urlopen(url).read().decode()) - if 'response' not in response: - raise self.Error(response) - return response['response'] + try: + with urllib.request.urlopen(url) as request: + response = json.loads(request.read().decode()) + if 'response' not in response: + raise InvalidResponseError(response) + return response['response'] + except URLError: + raise ConnectionError() @staticmethod def _format_param_values(xs): @@ -119,10 +138,3 @@ class API: Method.FRIENDS_GET, user_id=str(user_id), fields=self._format_param_values(fields))) - - class Error(RuntimeError): - def __init__(self, impl): - self._impl = impl - - def __str__(self): - return repr(self._impl) diff --git a/track_status.py b/track_status.py index 2761b2b..129b236 100644 --- a/track_status.py +++ b/track_status.py @@ -65,7 +65,10 @@ def loop_update_status(api, uids, timeout=DEFAULT_TIMEOUT): print_status(users[uid]) while True: time.sleep(timeout) - updated_users = update_status(api, uids) + try: + updated_users = update_status(api, uids) + except API.ConnectionError: + continue for uid in updated_users: if users[uid].is_online() != updated_users[uid].is_online(): users[uid] = updated_users[uid] -- cgit v1.2.3