-
Notifications
You must be signed in to change notification settings - Fork 99
all tasks OOP #161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
all tasks OOP #161
Conversation
| @@ -0,0 +1,39 @@ | |||
| name: CI | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
название кнш не очень, на работе осмысленно называй
| - name: Auto-fix code with Ruff | ||
| run: | | ||
| ruff check . --fix --line-length 88 || true |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
мы в ci не запускаем фиксы через линтеры, потому что они так коммитом не фиксируются. запускаем только ruff check и ruff fix --check (чисто проверки без форматирования). Команды с форматированием можно в пре-коммите запустить
| - name: Install dependencies | ||
| run: | | ||
| python -m pip install --upgrade pip | ||
| pip install ruff |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно ещё закэшировать установку ruff. и лучше указывать точную версию
|
|
||
| def _get(self, endpoint: str = "", **kwargs): | ||
| url = f"{self.base_url}{endpoint}" | ||
| print(f"[GET] {url}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
никаких print. только logging или loguru
|
|
||
| class BaseHTTPClient(ABC): | ||
|
|
||
| def __init__(self, base_url: str, headers: dict = None): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dict[Any, Any]
| self.base_url = base_url.rstrip("/") | ||
| self.headers = headers or {} | ||
|
|
||
| def _get(self, endpoint: str = "", **kwargs): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
надо показывать, что возвращает функция
| class Cloudflare(BaseHTTPClient): | ||
| def __init__(self, api_key: str = None, acc_id: str = None): | ||
| self.api_key = api_key or os.getenv("CLOUDFLARE_API_KEY") | ||
| self.acc_id = acc_id or os.getenv("CLOUDFLARE_ACCOUNT_ID") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
переменные окружения тянем в отдельном файле config.py и импортируем оттуда. для получения переменных можно тянуть их через starlette emvironment, а сами настройки хранить в pydantic base settings
| "Content-Type": "application/json" | ||
| } | ||
| super().__init__(base_url=base_url, headers=headers) | ||
| def _make_request(self, text: str): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
не типизируешь возвращаемые значения
| try: | ||
| data = self._make_request(text) | ||
| return data.get('result', {}).get('response', "No response") | ||
| except Exception as e: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
не надо использовать try except внутри методов. просто прокидывай исключение на самый верх и лови его в fastapi.exception_handler
|
|
||
| + 1.После того, как список оперативной памяти изменился на файл проекта, мы получаем доступ к данным хранилища даже после перезапуска приложения, данные не исчезают, а остаются в списке | ||
| + 2.Можно открыть файл и редактировать его вручную | ||
| + 3.Так как json файл является локальным, то при создании копий приложения, у них будут разные файлы tasks.json |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
к файлу может быть конкурентный доступ
| + Плюсы: Поддержка транзакций, масштабирование и надежность | ||
| + Минусы: Сложная настройка | ||
| ----------------------------------------------------------------------------------------------------------------------------- | ||
| Состояние гонки, это когда два разработчика делают одно и то же в коде и возникает конфликт(данные одного разработчика перезаписывают данные другого. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
не два разработчика в коде что-то делают, а два процесса/потока/клиента одновременно обращаются к одним данным
|
|
||
| return storage.load() | ||
| #create a new task with id, name, and status | ||
| @app.post("/tasks") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
у декораторов эндпоинтов есть такой аргумент как response_model, его надо заполнять. там должна быть pydantic модель. вообще вся работа в коде и особенно в эндпоинтах должна производиться через pydantic модели. они везде принимаются и возвращаются, никаких json и dict
| 'Accept': 'application/vnd.github+json' | ||
| } | ||
| super().__init__(base_url=base_url, headers=headers) | ||
| def _make_request(self, *args, **kwargs): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
нарушение I из SOLID
| def _make_request(self, *args, **kwargs): | ||
| pass | ||
| # loading task list from gist | ||
| def load(self) -> list[dict]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тут pydantic надо возвращать
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ну и не только тут, а вообще везде где dict юзаешь
| @@ -0,0 +1 @@ | |||
| [{"id": 1, "name": "finaltask", "condition": "updated"}, {"id": 2, "name": "totaltask", "condition": "updated"}, {"id": 3, "name": "Task3", "condition": "new"}] No newline at end of file | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше не пушить этот файл в гит. добавь в gitignore
| def load(self): | ||
| with open(self.file, 'r', encoding = 'utf-8') as f: | ||
| return json.load(f) | ||
| def save(self, tasks): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
типизацию куда потерял
LilChichaaa
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
оставил коммы
No description provided.