Skip to content

Conversation

@Krabler228
Copy link

  1. Нашел конфликт
  2. Исправил конфликт
  3. Прогнал через линтер
  4. дикий огурец


jobs:
ruff:
runs-on: ubuntu-latest

Choose a reason for hiding this comment

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

latest образ кринж юзать, используй конкретную версию и по возможности слим

python-version: "3.11"

- name: Install Ruff
run: pip install ruff

Choose a reason for hiding this comment

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

тут лучше тоже конкретную версию ставить + закэшировать можно установку

try:
return json.load(file)
except json.JSONDecodeError:
return []

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 ловить исключения

from settings import JSONBIN_API_KEY, JSONBIN_BIN_ID, CF_API_TOKEN, CF_ACCOUNT_ID, CF_MODEL

JSONBIN_BASE = "https://api.jsonbin.io/v3/b"
CF_BASE = "https://api.cloudflare.com/client/v4"

Choose a reason for hiding this comment

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

переменные с url лучше тянуть из env через pydanric base settings или starlette и хранить в отдельном файле с конфигом

self.path = Path(path)
if not self.path.exists():
self.save([])
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 модели вместо дикта

r.raise_for_status()
return r.json()["record"]
def save(self, data: list[dict]) -> None:
r = requests.put(f"{JSONBIN_BASE}/{self.bin_id}", headers=self.headers, json=data, timeout=10)

Choose a reason for hiding this comment

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

длиннющая строка, можно url в отдельную переменную выше записать

def __init__(self):
self.url = f"{CF_BASE}/accounts/{CF_ACCOUNT_ID}/ai/run/{CF_MODEL}"
self.headers = {"Authorization": f"Bearer {CF_API_TOKEN}"}
def explain(self, text: str) -> str:

Choose a reason for hiding this comment

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

ты мог сделать методы post, get и тд вместо explain, save и тд, и вынести их в общий родительский класс

def get_tasks() -> list[dict]:
return storage.load()

@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 модель

def to_dict(self):
return {"task_id": self.task_id, "name": self.name, "status": self.status}

@app.get("/tasks")

Choose a reason for hiding this comment

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

коннекти эндпоинты к роутеру , а не к приложению фастапи

- отваливаются данные при перезапуске
Хранение в json
+ задачи сохраняются на диск и не пропадают
- все еще stateful плюс проблемы с одновременным сохранением и тд

Choose a reason for hiding this comment

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

не stateful. когда состояние хранится во внешнем хранилище, это уже стейтлесс


JSONBIN_API_KEY = os.getenv("JSONBIN_API_KEY")
JSONBIN_BIN_ID = os.getenv("JSONBIN_BIN_ID")
CF_API_TOKEN = os.getenv("CF_API_TOKEN")

Choose a reason for hiding this comment

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

нормас, но можно юзать starlette config либо pydantic base settings, так чище и моднее

JSONBIN_BIN_ID = os.getenv("JSONBIN_BIN_ID")
CF_API_TOKEN = os.getenv("CF_API_TOKEN")
CF_ACCOUNT_ID = os.getenv("CF_ACCOUNT_ID")
CF_MODEL = os.getenv("CF_MODEL", "@cf/meta/llama-3.1-8b-instruct")

Choose a reason for hiding this comment

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

можно файл .env.example ещё пушить с пустыми переменными

Хранени
Состояние гонки
Это ситуация, когда два клиента одновременно читают старое состояние и перезаписывают друг друга. - это термин из интернета
Как я понял: состояние гонки это когда один файл берут два человека и пытаются с ним работать(не получится - файл то один).

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