summaryrefslogtreecommitdiff
path: root/day4/task3/db.py
blob: c23e9fb3e6980173e219c2ec81d0a51b99784e02 (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import re
import bisect
from datetime import datetime


db = []


def search_by_date(hour, minute=None, second=None, data=None):
    low = [hour]
    high = [hour]
    if minute is not None:
        low.append(minute)
        high.append(minute)

        if second is not None:
            low.append(second)
            high.append(second + 1)
        else:
            high.append(60)
    else:
        high.append(60)

    left = bisect.bisect_left(db, tuple(low))
    right = bisect.bisect_left(db, tuple(high))
    return [t[4] for t in db[left:right] if data in t[3]]


def open_log(path):
    try:
        f = open(path)

    except FileNotFoundError:
        print('Файл с логом не обнаружен')
        return

    except PermissionError:
        print('Файл с логом не доступен для чтения')
        return

    return f


# Возвращает значение успешности инициализации базы данных
def init(path) -> bool:
    f = open_log(path)
    if f is None:
        return False

    matcher = re.compile(r'\[(?P<date>.*?)\]\[(?P<type>.*?)\]\[(?P<module>.*?)\]\[(?P<id>.*?)\] (?P<text>.*)')

    lines = f.readlines()
    f.close()
    for line in lines:
        line = line.strip()
        match = re.match(matcher, line)

        if match:
            try:
                date = datetime.strptime(match.group('date'), '%c')
            except ValueError:
                print(f'Ошибка при разборе строки (Неверный формат даты):\n{line}')
                continue

            module = match.group('module')

            db.append((date.hour, date.minute, date.second, module, line))

        else:
            print(f'Ошибка при разборе строки:\n{line}')

    db.sort()
    return True