Привет! Помоги починить ошибку (использую tdlib хочу сделать свой клиент телеграмм):


Process SpawnProcess-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/uvicorn/_subprocess.py", line 80, in subprocess_started
    target(sockets=sockets)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/uvicorn/server.py", line 65, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/uvicorn/server.py", line 69, in serve
    await self._serve(sockets)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/uvicorn/server.py", line 76, in _serve
    config.load()
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/uvicorn/config.py", line 434, in load
    self.loaded_app = import_from_string(self.app)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/uvicorn/importer.py", line 19, in import_from_string
    module = importlib.import_module(module_str)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Users/sergeilogachev/PycharmProjects/tg/main.py", line 7, in <module>
    from auth import router as auth_router, manager
  File "/Users/sergeilogachev/PycharmProjects/tg/auth.py", line 7, in <module>
    from schemas import UserCreate, UserInDB
  File "/Users/sergeilogachev/PycharmProjects/tg/schemas.py", line 10, in <module>
    class UserInDB(BaseModel):
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/_internal/_model_construction.py", line 224, in __new__
    complete_model_class(
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/_internal/_model_construction.py", line 577, in complete_model_class
    schema = cls.__get_pydantic_core_schema__(cls, handler)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/main.py", line 671, in __get_pydantic_core_schema__
    return handler(source)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/_internal/_schema_generation_shared.py", line 83, in __call__
    schema = self._handler(source_type)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/_internal/_generate_schema.py", line 655, in generate_schema
    schema = self._generate_schema_inner(obj)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/_internal/_generate_schema.py", line 924, in _generate_schema_inner
    return self._model_schema(obj)
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/_internal/_generate_schema.py", line 676, in _model_schema
    check_decorator_fields_exist(
  File "/Users/sergeilogachev/PycharmProjects/tg/.venv/lib/python3.10/site-packages/pydantic/_internal/_generate_schema.py", line 198, in check_decorator_fields_exist
    raise PydanticUserError(
pydantic.errors.PydanticUserError: Decorators defined with incorrect fields: schemas.UserInDB:4337932896.validate_my_field (use check_fields=False if you're inheriting from the model and intended this)

For further information visit https://errors.pydantic.dev/2.9/u/decorator-missing-field







main.py: [
from fastapi import FastAPI, Request, Depends, Form, UploadFile, File, HTTPException, status
from fastapi.templating import Jinja2Templates
from fastapi.responses import RedirectResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from database import database, engine, metadata
from auth import router as auth_router, manager
from models import Base
from schemas import User
from tdlib_manager import get_client, close_client
import os
import aiofiles


app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")
auth_manager = manager

app.include_router(auth_router, prefix='/auth')


@app.on_event("startup")
async def startup():
    await database.connect()
    metadata.create_all(engine)


@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()


@app.get('/')
async def index(request: Request, user=Depends(manager)):
    user_id = user['id']
    client = await get_client(user_id)

    auth_state = await client.get_authorization_state()
    if auth_state['@type'] != 'authorizationStateReady':
        return RedirectResponse(url='/start')

    chats = await client.get_main_list_chats(limit=50)
    return templates.TemplateResponse('index.html', {'request': request, 'chats': chats, 'user': user})


@app.get('/start')
async def start_page(request: Request, user=Depends(manager)):
    user_id = user['id']
    client = await get_client(user_id)
    auth_state = await client.get_authorization_state()

    if auth_state['@type'] == 'authorizationStateWaitPhoneNumber':
        return templates.TemplateResponse('auth/login_phone.html', {'request': request})
    elif auth_state['@type'] == 'authorizationStateWaitCode':
        return templates.TemplateResponse('auth/login_code.html', {'request': request})
    elif auth_state['@type'] == 'authorizationStateWaitPassword':
        return templates.TemplateResponse('auth/login_password.html', {'request': request})
    elif auth_state['@type'] == 'authorizationStateReady':
        return RedirectResponse(url='/')
    else:
        return 'Неизвестное состояние авторизации.'


@app.post('/start')
async def start(request: Request, user=Depends(manager), phone_number: str = Form(None), code: str = Form(None), password: str = Form(None)):
    user_id = user['id']
    client = await get_client(user_id)
    auth_state = await client.get_authorization_state()

    try:
        if auth_state['@type'] == 'authorizationStateWaitPhoneNumber':
            await client.set_authentication_phone_number(phone_number)
        elif auth_state['@type'] == 'authorizationStateWaitCode':
            await client.check_authentication_code(code)
        elif auth_state['@type'] == 'authorizationStateWaitPassword':
            await client.check_authentication_password(password)
    except Exception as e:
        error = str(e)
        if auth_state['@type'] == 'authorizationStateWaitPhoneNumber':
            return templates.TemplateResponse('auth/login_phone.html', {'request': request, 'error': error})
        elif auth_state['@type'] == 'authorizationStateWaitCode':
            return templates.TemplateResponse('auth/login_code.html', {'request': request, 'error': error})
        elif auth_state['@type'] == 'authorizationStateWaitPassword':
            return templates.TemplateResponse('auth/login_password.html', {'request': request, 'error': error})

    return RedirectResponse(url='/start')


@app.get('/chat/{chat_id}')
async def chat_page(request: Request, chat_id: int, user=Depends(manager)):
    user_id = user['id']
    client = await get_client(user_id)
    auth_state = await client.get_authorization_state()

    if auth_state['@type'] != 'authorizationStateReady':
        return RedirectResponse(url='/start')

    history = await client.get_chat_history(chat_id=chat_id, limit=50)
    messages = history.messages
    return templates.TemplateResponse('chat.html', {'request': request, 'messages': messages, 'chat_id': chat_id, 'user': user})


@app.post('/chat/{chat_id}')
async def send_message(request: Request, chat_id: int, user=Depends(manager), message: str = Form(None), file: UploadFile = File(None)):
    user_id = user['id']
    client = await get_client(user_id)

    if file:
        upload_dir = f'uploads/{user_id}'
        os.makedirs(upload_dir, exist_ok=True)
        file_path = os.path.join(upload_dir, file.filename)
        async with aiofiles.open(file_path, 'wb') as outfile:
            content = await file.read()
            await outfile.write(content)
        await client.send_document(chat_id=chat_id, document=file_path, caption=message)
    else:
        await client.send_text(chat_id=chat_id, text=message)

    return RedirectResponse(url=f'/chat/{chat_id}', status_code=status.HTTP_302_FOUND)


@app.get('/download/{user_id}/{filename}')
async def download_file(user_id: int, filename: str):
    file_path = os.path.join('uploads', str(user_id), filename)
    if os.path.exists(file_path):
        async def iterfile():
            async with aiofiles.open(file_path, 'rb') as f:
                while True:
                    chunk = await f.read(1024)
                    if not chunk:
                        break
                    yield chunk
        return StreamingResponse(iterfile(), media_type='application/octet-stream', headers={
            "Content-Disposition": f"attachment; filename={filename}"
        })
    else:
        raise HTTPException(status_code=404, detail="Файл не найден")
]







schemas.py: [
from pydantic import BaseModel, validator


class UserCreate(BaseModel):
    username: str
    password: str


class UserInDB(BaseModel):
    id: int
    username: str
    hashed_password: str

    class Config:
        from_attributes = True  # Replace orm_mode = True

    @validator('my_field')
    def validate_my_field(cls, value):
        # Validation logic
        return value

class User(BaseModel):
    id: int
    username: str

    class Config:
        from_attributes = True  # Replace orm_mode = True
]