update app/storage.py
Browse files- app/storage.py +46 -0
app/storage.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Optional
|
| 2 |
+
from app.models import Proxy
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import asyncio
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class InMemoryStorage:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
self._proxies: Dict[str, Proxy] = {}
|
| 10 |
+
self._lock = asyncio.Lock()
|
| 11 |
+
|
| 12 |
+
async def add_proxies(self, proxies: List[Proxy]) -> int:
|
| 13 |
+
async with self._lock:
|
| 14 |
+
added = 0
|
| 15 |
+
for proxy in proxies:
|
| 16 |
+
key = f"{proxy.ip}:{proxy.port}:{proxy.protocol}"
|
| 17 |
+
if key not in self._proxies:
|
| 18 |
+
self._proxies[key] = proxy
|
| 19 |
+
added += 1
|
| 20 |
+
return added
|
| 21 |
+
|
| 22 |
+
async def get_all_proxies(
|
| 23 |
+
self, protocol: Optional[str] = None, limit: int = 100, offset: int = 0
|
| 24 |
+
) -> List[Proxy]:
|
| 25 |
+
async with self._lock:
|
| 26 |
+
proxies = list(self._proxies.values())
|
| 27 |
+
|
| 28 |
+
if protocol:
|
| 29 |
+
proxies = [p for p in proxies if p.protocol == protocol]
|
| 30 |
+
|
| 31 |
+
return proxies[offset : offset + limit]
|
| 32 |
+
|
| 33 |
+
async def get_count(self, protocol: Optional[str] = None) -> int:
|
| 34 |
+
async with self._lock:
|
| 35 |
+
if protocol:
|
| 36 |
+
return len(
|
| 37 |
+
[p for p in self._proxies.values() if p.protocol == protocol]
|
| 38 |
+
)
|
| 39 |
+
return len(self._proxies)
|
| 40 |
+
|
| 41 |
+
async def clear(self):
|
| 42 |
+
async with self._lock:
|
| 43 |
+
self._proxies.clear()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
storage = InMemoryStorage()
|