Skip to content

Conversation

@maloyparser
Copy link

No description provided.

@@ -0,0 +1,39 @@
name: CI

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

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

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}")

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):

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):

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")

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):

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:

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

к файлу может быть конкурентный доступ

+ Плюсы: Поддержка транзакций, масштабирование и надежность
+ Минусы: Сложная настройка
-----------------------------------------------------------------------------------------------------------------------------
Состояние гонки, это когда два разработчика делают одно и то же в коде и возникает конфликт(данные одного разработчика перезаписывают данные другого.

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")

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):

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]:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут pydantic надо возвращать

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

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):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

типизацию куда потерял

Copy link

@LilChichaaa LilChichaaa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

оставил коммы

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants