Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions client.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import asyncio
import json
from typing import Any, Dict, List
from typing import Any, Dict #List не используется
from urllib.request import urlopen


class HttpClient:
async def fetch_json(self, url: str) -> Dict[str, Any]:
async def format_json(self, url: str) -> Dict[str, Any]: #Без глаголов
resp = urlopen(url, timeout=3)
raw = resp.read()
await asyncio.sleep(0)
return json.loads(raw)
return dict(json.loads(raw)) #Вернуть словарь


def is_valid_user(payload: Dict[str, Any]) -> bool:
Expand Down
6 changes: 3 additions & 3 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from dataclasses import dataclass
from typing import Any, Dict, Optional
from dataclasses import dataclass, field
from typing import Any, Optional #Dict


@dataclass
class User:
id: int
name: str
email: Optional[str] = None
meta: Dict[str, Any] = {}
meta: dict[str, Any] = field(default_factory=dict) #{} ошибка 1-го словаря
4 changes: 2 additions & 2 deletions repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ def __init__(self):
self.storage = {}
self.last_saved_at = None

def save(self, key, value):
def save(self, key: str, value: str): #Аннотации
time.sleep(0.05)
self.storage[key] = value
self.last_saved_at = time.time()

def get(self, key, default=None):
def get(self, key: str, default: str | None =None): #Аннотации
return self.storage.get(key, default)

def all(self):
Expand Down
17 changes: 10 additions & 7 deletions service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import asyncio
from typing import Any, Dict, List, Tuple

from typing import Any #List, Tuple
from models import User
from repo import InMemoryRepo
from client import HttpClient, is_valid_user
Expand All @@ -11,23 +10,26 @@ def __init__(self, repo: InMemoryRepo):
self.repo = repo
self.client = HttpClient()

def parse(self, data: Dict[str, Any]) -> User:
@staticmethod # Статически
def parse(data: dict[str, Any]) -> User: # Глаголы, self не используется
return User(
id=int(data["id"]),
name=data["name"].strip(),
email=data.get("email"),
meta=data.get("meta", {}),
)

async def sync_users(self, urls: List[str]) -> Tuple[int, List[str]]:
@staticmethod # Статически
async def sync_users(self, urls: list[str]) -> tuple[int, list[str]]:
tasks = []
errors = []

for url in urls:
tasks.append(asyncio.create_task(self.client.fetch_json(url)))
tasks.append(asyncio.create_task(self.client.format_json(url))) # format_json

results = await asyncio.gather(*tasks, return_exceptions=True)


for i, r in enumerate(results):
if isinstance(r, Exception):
errors.append(f"{urls[i]}: {r}")
Expand All @@ -44,7 +46,7 @@ async def sync_users(self, urls: List[str]) -> Tuple[int, List[str]]:
return len(urls) - len(errors), errors


def calc_stats(repo: InMemoryRepo) -> Dict[str, Any]:
def calc_stats(repo: InMemoryRepo) -> dict[str, Any]:
users = repo.all().values()
total = len(list(users))
with_email = len([u for u in users if u.email])
Expand All @@ -58,4 +60,5 @@ def calc_stats(repo: InMemoryRepo) -> Dict[str, Any]:
"total": total,
"with_email": with_email,
"top_domain": max(domains, key=domains.get) if domains else None,
}
}