Skip to content

Commit 4942af2

Browse files
committed
fix: added custom PubSub and TimedCache
1 parent 9b08d0e commit 4942af2

File tree

4 files changed

+134
-61
lines changed

4 files changed

+134
-61
lines changed

.flake8

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,6 @@
33
exclude =
44
migrations
55

6-
max-line-length = 120
6+
max-line-length = 120
7+
8+
ignore = D

multifilter.py

-60
This file was deleted.

my_PubSub.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""Cunsom PubSub implementation."""
2+
3+
4+
class PubSub:
5+
"""Custom PubSub class."""
6+
7+
def __init__(self):
8+
"""Initialize subscribers dictionary."""
9+
self.subscribers = {}
10+
11+
def subscribe(self, event_name):
12+
"""Subscribe to event_name."""
13+
14+
def decorator(func):
15+
"""Add function to subscribers list."""
16+
if event_name not in self.subscribers:
17+
self.subscribers[event_name] = []
18+
self.subscribers[event_name].append(func)
19+
20+
return func
21+
22+
return decorator
23+
24+
def emit(self, event_name, data):
25+
"""Emit event_name with data."""
26+
if event_name in self.subscribers:
27+
for func in self.subscribers[event_name]:
28+
func(data)
29+
30+
def off(self, event_name, func):
31+
"""Unsubscribe from event_name."""
32+
if event_name in self.subscribers:
33+
self.subscribers[event_name] = [f for f in self.subscribers[event_name] if f != func]
34+
35+
36+
# Пример использования
37+
pubSub = PubSub()
38+
39+
40+
@pubSub.subscribe("event1")
41+
def log1(data):
42+
"""Test function 1."""
43+
print("event1", data)
44+
45+
46+
@pubSub.subscribe("event2")
47+
def log2(data):
48+
"""Test function 2."""
49+
print("event2", data)
50+
51+
52+
@pubSub.subscribe("event1")
53+
def log3(data):
54+
"""Test function 3."""
55+
print("event1-1111", data)
56+
57+
58+
# Эмитим событие до отписки
59+
pubSub.emit("event1", "hello")
60+
pubSub.emit("event2", "hello")
61+
62+
# Отписываем log3 от event1
63+
pubSub.off("event1", log3)
64+
65+
# Эмитим событие после отписки
66+
pubSub.emit("event1", "hello again")
67+
pubSub.emit("event2", "hello again")

my_TimedCache.py

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""Custom implementation of a timed cache."""
2+
3+
import threading
4+
import time
5+
6+
7+
class TimedCache:
8+
"""Timed cache class."""
9+
10+
def __init__(self):
11+
"""Initialize cache and lock."""
12+
self.cache = {}
13+
self.lock = threading.Lock()
14+
15+
def set(self, key, value, ttl):
16+
"""Set value with TTL."""
17+
expiration_time = time.time() + ttl
18+
with self.lock:
19+
self.cache[key] = (value, expiration_time)
20+
# Запускаем поток для удаления элемента по истечении времени
21+
threading.Thread(target=self._remove_after_ttl, args=(key, ttl)).start()
22+
23+
def get(self, key):
24+
"""Get value by key."""
25+
with self.lock:
26+
if key in self.cache:
27+
value, expiration_time = self.cache[key]
28+
if time.time() < expiration_time:
29+
return value
30+
else:
31+
del self.cache[key]
32+
return None
33+
return None
34+
35+
def _remove_after_ttl(self, key, ttl):
36+
"""Remove key after TTL."""
37+
time.sleep(ttl)
38+
with self.lock:
39+
if key in self.cache:
40+
value, expiration_time = self.cache[key]
41+
if time.time() >= expiration_time:
42+
del self.cache[key]
43+
44+
def __contains__(self, key):
45+
"""Check if key is in cache and not expired."""
46+
with self.lock:
47+
if key in self.cache:
48+
_, expiration_time = self.cache[key]
49+
if time.time() < expiration_time:
50+
return True
51+
else:
52+
del self.cache[key]
53+
return False
54+
55+
56+
# Пример использования
57+
cache = TimedCache()
58+
cache.set("foo", "bar", 5) # Устанавливаем значение с TTL 5 секунд
59+
60+
print(cache.get("foo")) # Вывод: bar
61+
62+
time.sleep(6)
63+
64+
print(cache.get("foo")) # Вывод: None (значение истекло)

0 commit comments

Comments
 (0)