@vadik007

Почему выходит ошибка при валидации данных при post запросе?

Всем доброго дня! Столкнулся с проблемой. Когда пробую добавить вот эти данные
64be721456e42339781066.png
{
  "name": "фффффффффффффффффффффффффффффффффффффффффф",
  "inn": 64445664,
  "kpp": 35645,
  "address_juridical": "прварвпара",
  "address_actual": "прапрарвапр",
  "phone": "89325542525",
  "email": "sdasdas@mail.ru",
  "hide": true,
  "id_type_organization": 1,
  "organization_id": 1
}

Вот ошибка
INFO:     127.0.0.1:54607 - "POST /contractors HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 426, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 84, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\applications.py", line 290, in __call__
    await super().__call__(scope, receive, send)
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\applications.py", line 122, in __call__
    await self.middleware_stack(scope, receive, send)
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
    raise exc
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
    raise exc
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
    await self.app(scope, receive, sender)
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 20, in __call__
    raise e
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 17, in __call__
    await self.app(scope, receive, send)
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\routing.py", line 718, in __call__
    await route.handle(scope, receive, send)
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\routing.py", line 276, in handle
    await self.app(scope, receive, send)
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\starlette\routing.py", line 66, in app
    response = await func(request)
               ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\routing.py", line 259, in app
    content = await serialize_response(
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ПК-1\AppData\Local\Programs\Python\Python311\Lib\site-packages\fastapi\routing.py", line 145, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for ContractorsAddSchemas
response
  none is not an allowed value (type=type_error.none.not_allowed)

вот моя модель и схема
class Contractors(Base):
    """
    Модель контрагентов
    """
    __tablename__ = 'contractors'

    id: Mapped[int] = mapped_column(primary_key=True, unique=True)
    name: Mapped[str] = mapped_column(nullable=False)
    inn: Mapped[int] = mapped_column(nullable=False)
    kpp: Mapped[int] = mapped_column(nullable=False)
    address_juridical: Mapped[str]
    address_actual: Mapped[str]
    phone: Mapped[str] = mapped_column(unique=True)
    email: Mapped[str] = mapped_column(nullable=False)
    hide: Mapped[bool] = mapped_column(nullable=True, default=True)

    id_type_organization: Mapped[int] = mapped_column(ForeignKey("type_organization.id"))
    type_organization: Mapped["type_organization"] = relationship("TypeOrganization", back_populates='contractors')

    organization_id: Mapped[int] = mapped_column(ForeignKey("organization.id"))
    organization: Mapped["organization"] = relationship("Organization", back_populates='contractors')


class ContractorsAddSchemas(BaseModel):
    name: str
    inn: int
    kpp: int
    address_juridical: str
    address_actual: str
    phone: str
    email: str
    hide: bool
    id_type_organization: int
    organization_id: int

    class Config:
        orm_mode = True


вот дао(сервис)
@classmethod
    async def add(cls, **data: dict):
        async with async_session_maker() as session:
            query = insert(cls.model).values(**data)
            print(data)
            # print(query)
            await session.execute(query)
            await session.commit()

@router.post('')
async def add_contractors(contractor: dict) -> ContractorsAddSchemas:
    return await ContractorsDAO.add(**contractor)

вот репозиторий
Дело в том что данные в базу данных добавляются, хотя выходит ошибка. В ошибке ругается на неправильный тип данных, json валидный, все передаваемые данные соответствуют типу данных в schemas. fastapi==0.99.1 pydantic==1.10.11
Подскажите пожалуйста в чем ошибка и как ее исправить
  • Вопрос задан
  • 353 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы