aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/vk
diff options
context:
space:
mode:
authorEgor Tensin <Egor.Tensin@gmail.com>2019-12-23 07:20:36 +0300
committerEgor Tensin <Egor.Tensin@gmail.com>2019-12-23 07:20:36 +0300
commit7b8cc8a9f455eda41b9c7d70f4561a84fcda941e (patch)
treeb9e262e9a1dbb663c3b9f704a9fe4daf54be0ce9 /vk
parentTravis: online_sessions.sh: refactoring (diff)
downloadvk-scripts-7b8cc8a9f455eda41b9c7d70f4561a84fcda941e.tar.gz
vk-scripts-7b8cc8a9f455eda41b9c7d70f4561a84fcda941e.zip
pylint/pep8 fixes
Diffstat (limited to 'vk')
-rw-r--r--vk/api.py23
-rw-r--r--vk/error.py3
-rw-r--r--vk/last_seen.py4
-rw-r--r--vk/platform.py2
-rw-r--r--vk/tracking/db/backend/csv.py2
-rw-r--r--vk/tracking/db/backend/log.py1
-rw-r--r--vk/tracking/db/backend/null.py2
-rw-r--r--vk/tracking/db/format.py29
-rw-r--r--vk/tracking/db/io.py8
-rw-r--r--vk/tracking/db/meta.py2
-rw-r--r--vk/tracking/db/record.py1
-rw-r--r--vk/tracking/db/timestamp.py1
-rw-r--r--vk/tracking/online_sessions.py2
-rw-r--r--vk/tracking/status_tracker.py4
-rw-r--r--vk/user.py21
15 files changed, 73 insertions, 32 deletions
diff --git a/vk/api.py b/vk/api.py
index d79122d..0ba2f44 100644
--- a/vk/api.py
+++ b/vk/api.py
@@ -3,8 +3,7 @@
# For details, see https://github.com/egor-tensin/vk-scripts.
# Distributed under the MIT License.
-from collections import Iterable
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from enum import Enum
import json
from urllib.error import URLError
@@ -14,21 +13,24 @@ from urllib.request import urlopen
import vk.error
from vk.user import User
+
def _split_url(url):
return urllib.parse.urlsplit(url)[:3]
+
def _is_empty_param_value(value):
return isinstance(value, str) and not value
+
def _filter_empty_params(params, empty_params=False):
if empty_params:
return params
if isinstance(params, Mapping):
return {name: value for name, value in params.items() if not _is_empty_param_value(value)}
- elif isinstance(params, Iterable):
+ if isinstance(params, Iterable):
return [(name, value) for name, value in params if not _is_empty_param_value(value)]
- else:
- raise TypeError()
+ raise TypeError()
+
def _build_url(scheme, host, path, params=None, empty_params=False):
if params is None:
@@ -43,6 +45,7 @@ def _build_url(scheme, host, path, params=None, empty_params=False):
path = urllib.parse.quote(path)
return urllib.parse.urlunsplit((scheme, host, path, params, ''))
+
def _join_param_values(values):
if isinstance(values, str):
return values
@@ -50,13 +53,16 @@ def _join_param_values(values):
return ','.join(map(str, values))
return values
+
def _join_path(base, url):
if not base.endswith('/'):
base += '/'
return urllib.parse.urljoin(base, url)
+
ACCESS_TOKEN = '9722cef09722cef09722cef071974b8cbe997229722cef0cbabfd816916af6c7bd37006'
+
class Version(Enum):
V5_73 = '5.73'
DEFAULT = V5_73
@@ -64,6 +70,7 @@ class Version(Enum):
def __str__(self):
return self.value
+
class Language(Enum):
EN = 'en'
DEFAULT = EN
@@ -71,6 +78,7 @@ class Language(Enum):
def __str__(self):
return self.value
+
class Method(Enum):
USERS_GET = 'users.get'
FRIENDS_GET = 'friends.get'
@@ -78,6 +86,7 @@ class Method(Enum):
def __str__(self):
return self.value
+
class CommonParameters(Enum):
ACCESS_TOKEN = 'access_token'
VERSION = 'v'
@@ -86,6 +95,7 @@ class CommonParameters(Enum):
def __str__(self):
return self.value
+
class API:
_ROOT_URL = 'https://api.vk.com/method/'
@@ -136,4 +146,5 @@ class API:
fields=_join_param_values(fields))
if 'items' not in response:
raise vk.error.InvalidAPIResponseError(response)
- return self._filter_response_with_users(response['items'], deactivated_users)
+ return self._filter_response_with_users(response['items'],
+ deactivated_users)
diff --git a/vk/error.py b/vk/error.py
index 3a309c3..5f71e47 100644
--- a/vk/error.py
+++ b/vk/error.py
@@ -3,9 +3,11 @@
# For details, see https://github.com/egor-tensin/vk-scripts.
# Distributed under the MIT License.
+
class APIError(RuntimeError):
pass
+
class InvalidAPIResponseError(APIError):
def __init__(self, response):
super().__init__()
@@ -14,5 +16,6 @@ class InvalidAPIResponseError(APIError):
def __str__(self):
return str(self.response)
+
class APIConnectionError(APIError):
pass
diff --git a/vk/last_seen.py b/vk/last_seen.py
index 25975f2..cf76db5 100644
--- a/vk/last_seen.py
+++ b/vk/last_seen.py
@@ -11,6 +11,7 @@ from numbers import Integral, Real
from .platform import Platform
+
def _parse_time(x):
if isinstance(x, datetime):
if x.tzinfo is None or x.tzinfo.utcoffset(x) is None:
@@ -20,6 +21,7 @@ def _parse_time(x):
return datetime.fromtimestamp(x, tz=timezone.utc)
raise TypeError()
+
def _parse_platform(x):
if x in Platform:
return x
@@ -27,6 +29,7 @@ def _parse_platform(x):
return Platform.from_string(x)
return Platform(x)
+
class LastSeenField(Enum):
TIME = 'time'
PLATFORM = 'platform'
@@ -34,6 +37,7 @@ class LastSeenField(Enum):
def __str__(self):
return self.value
+
class LastSeen(MutableMapping):
@staticmethod
def from_api_response(source):
diff --git a/vk/platform.py b/vk/platform.py
index 8bf23c5..5cd78b8 100644
--- a/vk/platform.py
+++ b/vk/platform.py
@@ -6,6 +6,7 @@
from enum import Enum
import re
+
class Platform(Enum):
MOBILE = 1
IPHONE = 2
@@ -43,6 +44,7 @@ class Platform(Enum):
def get_descr_text_capitalized(self):
return self._capitalize_first_letter(self.get_descr_text())
+
_PLATFORM_DESCRIPTIONS = {
Platform.MOBILE: '"mobile" web version (or unrecognized mobile app)',
Platform.IPHONE: 'official iPhone app',
diff --git a/vk/tracking/db/backend/csv.py b/vk/tracking/db/backend/csv.py
index 4943ff2..43038e4 100644
--- a/vk/tracking/db/backend/csv.py
+++ b/vk/tracking/db/backend/csv.py
@@ -8,6 +8,7 @@ from ..io import FileReaderCSV, FileWriterCSV
from ..record import Record
from ..timestamp import Timestamp
+
class Writer(meta.Writer):
def __init__(self, fd):
self._writer = FileWriterCSV(fd)
@@ -30,6 +31,7 @@ class Writer(meta.Writer):
def _record_to_row(record):
return [str(record.get_timestamp())] + [str(record[field]) for field in record]
+
class Reader(meta.Reader):
def __init__(self, fd):
self._reader = FileReaderCSV(fd)
diff --git a/vk/tracking/db/backend/log.py b/vk/tracking/db/backend/log.py
index 814cabc..d301856 100644
--- a/vk/tracking/db/backend/log.py
+++ b/vk/tracking/db/backend/log.py
@@ -7,6 +7,7 @@ import logging
from .. import meta
+
class Writer(meta.Writer):
def __init__(self, fd):
self._logger = logging.getLogger(__file__)
diff --git a/vk/tracking/db/backend/null.py b/vk/tracking/db/backend/null.py
index 663af10..80a66b4 100644
--- a/vk/tracking/db/backend/null.py
+++ b/vk/tracking/db/backend/null.py
@@ -5,6 +5,7 @@
from .. import meta
+
class Writer(meta.Writer):
def __init__(self):
pass
@@ -18,6 +19,7 @@ class Writer(meta.Writer):
def on_connection_error(self, e):
pass
+
class Reader(meta.Reader):
def __init__(self):
pass
diff --git a/vk/tracking/db/format.py b/vk/tracking/db/format.py
index f9a670c..028d403 100644
--- a/vk/tracking/db/format.py
+++ b/vk/tracking/db/format.py
@@ -8,6 +8,7 @@ import sys
from . import backend, io
+
class Format(Enum):
CSV = 'csv'
LOG = 'log'
@@ -19,22 +20,20 @@ class Format(Enum):
def create_writer(self, fd=sys.stdout):
if self is Format.CSV:
return backend.csv.Writer(fd)
- elif self is Format.LOG:
+ if self is Format.LOG:
return backend.log.Writer(fd)
- elif self is Format.NULL:
+ if self is Format.NULL:
return backend.null.Writer()
- else:
- raise NotImplementedError('unsupported database format: ' + str(self))
+ raise NotImplementedError('unsupported database format: ' + str(self))
def open_output_file(self, path=None):
if self is Format.CSV:
return self._open_output_database_file(path)
- elif self is Format.LOG:
+ if self is Format.LOG:
return self._open_output_log_file(path)
- elif self is Format.NULL:
+ if self is Format.NULL:
return self._open_output_database_file(None)
- else:
- raise NotImplementedError('unsupported database format: ' + str(self))
+ raise NotImplementedError('unsupported database format: ' + str(self))
@staticmethod
def _open_output_log_file(path):
@@ -47,19 +46,17 @@ class Format(Enum):
def create_reader(self, fd=sys.stdin):
if self is Format.CSV:
return backend.csv.Reader(fd)
- elif self is Format.LOG:
+ if self is Format.LOG:
return NotImplementedError('cannot read from a log file')
- elif self is Format.NULL:
+ if self is Format.NULL:
return backend.null.Reader()
- else:
- raise NotImplementedError('unsupported database format: ' + str(self))
+ raise NotImplementedError('unsupported database format: ' + str(self))
def open_input_file(self, path=None):
if self is Format.CSV:
return io.open_input_text_file(path)
- elif self is Format.LOG:
+ if self is Format.LOG:
raise NotImplementedError('cannot read from a log file')
- elif self is Format.NULL:
+ if self is Format.NULL:
return io.open_input_text_file(None)
- else:
- raise NotImplementedError('unsupported database format: ' + str(self))
+ raise NotImplementedError('unsupported database format: ' + str(self))
diff --git a/vk/tracking/db/io.py b/vk/tracking/db/io.py
index 37d9c53..a89865f 100644
--- a/vk/tracking/db/io.py
+++ b/vk/tracking/db/io.py
@@ -7,6 +7,7 @@ from contextlib import contextmanager
import csv
import sys
+
class FileWriterCSV:
def __init__(self, fd=sys.stdout):
self._fd = fd
@@ -14,7 +15,7 @@ class FileWriterCSV:
@staticmethod
def _convert_row_old_python(row):
- if isinstance(row, list) or isinstance(row, tuple):
+ if isinstance(row, (list, tuple)):
return row
return list(row)
@@ -24,6 +25,7 @@ class FileWriterCSV:
self._writer.writerow(row)
self._fd.flush()
+
class FileReaderCSV:
def __init__(self, fd=sys.stdin):
self._reader = csv.reader(fd)
@@ -31,6 +33,7 @@ class FileReaderCSV:
def __iter__(self):
return iter(self._reader)
+
@contextmanager
def _open_file(path=None, default=None, **kwargs):
if path is None:
@@ -39,12 +42,15 @@ def _open_file(path=None, default=None, **kwargs):
with open(path, **kwargs) as fd:
yield fd
+
_DEFAULT_ENCODING = 'utf-8'
+
def open_output_text_file(path=None, mode='w'):
return _open_file(path, default=sys.stdout, mode=mode,
encoding=_DEFAULT_ENCODING)
+
def open_input_text_file(path=None):
return _open_file(path, default=sys.stdin, mode='r',
encoding=_DEFAULT_ENCODING)
diff --git a/vk/tracking/db/meta.py b/vk/tracking/db/meta.py
index 024d9d8..eb15c74 100644
--- a/vk/tracking/db/meta.py
+++ b/vk/tracking/db/meta.py
@@ -6,6 +6,7 @@
import abc
from collections.abc import Iterable
+
class Writer(metaclass=abc.ABCMeta):
@abc.abstractmethod
def on_initial_status(self, user):
@@ -19,6 +20,7 @@ class Writer(metaclass=abc.ABCMeta):
def on_connection_error(self, e):
pass
+
class Reader(Iterable, metaclass=abc.ABCMeta):
@abc.abstractmethod
def __iter__(self):
diff --git a/vk/tracking/db/record.py b/vk/tracking/db/record.py
index dfd47c6..6998238 100644
--- a/vk/tracking/db/record.py
+++ b/vk/tracking/db/record.py
@@ -12,6 +12,7 @@ from vk.user import User, UserField
from .timestamp import Timestamp
+
class Record(MutableMapping):
FIELDS = (
UserField.UID,
diff --git a/vk/tracking/db/timestamp.py b/vk/tracking/db/timestamp.py
index b2219ca..1309797 100644
--- a/vk/tracking/db/timestamp.py
+++ b/vk/tracking/db/timestamp.py
@@ -5,6 +5,7 @@
from datetime import datetime, timezone
+
class Timestamp:
@staticmethod
def _new():
diff --git a/vk/tracking/online_sessions.py b/vk/tracking/online_sessions.py
index 204e1cc..c43e11c 100644
--- a/vk/tracking/online_sessions.py
+++ b/vk/tracking/online_sessions.py
@@ -8,6 +8,7 @@ from collections.abc import MutableMapping
from datetime import timedelta
from enum import Enum
+
class Weekday(Enum):
MONDAY = 0
TUESDAY = 1
@@ -20,6 +21,7 @@ class Weekday(Enum):
def __str__(self):
return self.name[0] + self.name[1:].lower()
+
class OnlineSessionEnumerator(MutableMapping):
def __init__(self, time_from=None, time_to=None):
self._records = {}
diff --git a/vk/tracking/status_tracker.py b/vk/tracking/status_tracker.py
index 30e0f97..b87e059 100644
--- a/vk/tracking/status_tracker.py
+++ b/vk/tracking/status_tracker.py
@@ -11,6 +11,7 @@ import signal
import vk.error
from vk.user import UserField
+
class StatusTracker:
DEFAULT_TIMEOUT = 5
@@ -49,7 +50,8 @@ class StatusTracker:
_USER_FIELDS = UserField.DOMAIN, UserField.ONLINE, UserField.LAST_SEEN,
def _query_status(self, uids):
- user_list = self._api.users_get(uids, self._USER_FIELDS, deactivated_users=False)
+ user_list = self._api.users_get(uids, self._USER_FIELDS,
+ deactivated_users=False)
return {user.get_uid(): user for user in user_list}
def _notify_status(self, user):
diff --git a/vk/user.py b/vk/user.py
index c3c997b..eb65eaf 100644
--- a/vk/user.py
+++ b/vk/user.py
@@ -9,31 +9,33 @@ from enum import Enum
from .last_seen import LastSeen
+
def _parse_last_seen(x):
if isinstance(x, LastSeen):
return x
- elif isinstance(x, Mapping):
+ if isinstance(x, Mapping):
return LastSeen.from_api_response(x)
- else:
- raise TypeError()
+ raise TypeError()
+
def _parse_bool(x):
if isinstance(x, str):
if str(True) == x:
return True
- elif str(False) == x:
+ if str(False) == x:
return False
- else:
- raise ValueError()
- else:
- return bool(x)
+ raise ValueError()
+ return bool(x)
+
def _parse_hidden(x):
return _parse_bool(x)
+
def _parse_online_flag(x):
return _parse_bool(x)
+
class UserField(Enum):
UID = 'id'
FIRST_NAME = 'first_name'
@@ -48,6 +50,7 @@ class UserField(Enum):
def __str__(self):
return self.value
+
class DeactivationReason(Enum):
DELETED = 'deleted'
BANNED = 'banned'
@@ -55,9 +58,11 @@ class DeactivationReason(Enum):
def __str__(self):
return self.value
+
def _parse_deactivated(s):
return DeactivationReason(s)
+
class User(Hashable, MutableMapping):
@staticmethod
def from_api_response(source):