blob: e6077743407cd49c6865a39c6bf89a46e6f4c2b4 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# Copyright (c) 2016 Egor Tensin <Egor.Tensin@gmail.com>
# This file is part of the "VK scripts" project.
# For details, see https://github.com/egor-tensin/vk-scripts.
# Distributed under the MIT License.
from collections.abc import Iterable
import csv
from ..record import Record
from ..timestamp import Timestamp
class Writer:
def __init__(self, fd):
self._fd = fd
self._writer = csv.writer(fd, lineterminator='\n')
def on_initial_status(self, user):
self._write_record(user)
self._fd.flush()
def on_status_update(self, user):
self._write_record(user)
self._fd.flush()
def on_connection_error(self, e):
pass
def _write_record(self, user):
if not self:
return
self._write_row(self._record_to_row(Record.from_user(user)))
def _write_row(self, row):
self._writer.writerow(row)
@staticmethod
def _record_to_row(record):
return [str(record.get_timestamp())] + [str(record[field]) for field in record]
class Reader(Iterable):
def __init__(self, fd):
self._reader = csv.reader(fd)
def __iter__(self):
return map(Reader._record_from_row, self._reader)
@staticmethod
def _record_from_row(row):
record = Record(Timestamp.from_string(row[0]))
for i in range(len(Record.FIELDS)):
record[Record.FIELDS[i]] = row[i + 1]
return record
|