question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] When i try to response a sqlalchemy model then i get ValidationError

See original GitHub issue

Describe the bug I have simple user creation method:

    def create(self, login: str, password: str) -> models.User:
        if not password:
            raise RuntimeError('Password is empty')

        password = utils.generate_password_hash(password)

        user = models.User(login=login, password=password)
        session = self.session()
        session.add(user)
        session.commit()
        session.refresh(user)
        return user

and the model:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    login = Column(String(256))
    password = Column(String(1000))
    
    created_at = Column(DateTime, default=datetime.datetime.now)
    updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    removed_at = Column(DateTime, nullable=True)

and this endpoint:


@router.post('/users', status_code=HTTP_201_CREATED, response_model=schemas.UserOut)
def create_user(
        user_data: schemas.UserIn,
        res: UsersResource = Depends(get_users_res)
):
    user = res.create(user_data.login, user_data.password.get_secret_value())
    return user

with schemas:

class UserIn(BaseModel):
    login: str = Schema(..., min_length=3)
    password: SecretStr = Schema(..., min_length=5)

class UserOut(BaseModel):
    id: int
    login: str
    created_at: datetime.datetime
    updated_at: datetime.datetime
    removed_at: Optional[datetime.datetime]

When I try to make a request it falls with the following error:

core_1      | email-validator not installed, email fields will be treated as str.
core_1      | To install, run: pip install email-validator
core_1      | INFO: Started server process [1]
core_1      | INFO: Waiting for application startup.
core_1      | INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
core_1      | INFO: ('172.21.0.1', 44266) - "POST /api/v1/users HTTP/1.1" 500
core_1      | ERROR: Exception in ASGI application
core_1      | Traceback (most recent call last):
core_1      |   File "/usr/local/lib/python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 370, in run_asgi
core_1      |     result = await app(self.scope, self.receive, self.send)
core_1      |   File "/usr/local/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 37, in __call__
core_1      |     await self.app(scope, receive, send)
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/applications.py", line 133, in __call__
core_1      |     await self.error_middleware(scope, receive, send)
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 122, in __call__
core_1      |     raise exc from None
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 100, in __call__
core_1      |     await self.app(scope, receive, _send)
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 73, in __call__
core_1      |     raise exc from None
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 62, in __call__
core_1      |     await self.app(scope, receive, sender)
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 585, in __call__
core_1      |     await route(scope, receive, send)
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 207, in __call__
core_1      |     await self.app(scope, receive, send)
core_1      |   File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 40, in app
core_1      |     response = await func(request)
core_1      |   File "/usr/local/lib/python3.7/site-packages/fastapi/routing.py", line 122, in app
core_1      |     skip_defaults=response_model_skip_defaults,
core_1      |   File "/usr/local/lib/python3.7/site-packages/fastapi/routing.py", line 54, in serialize_response
core_1      |     raise ValidationError(errors)
core_1      | pydantic.error_wrappers.ValidationError: 1 validation error
core_1      | response
core_1      |   value is not a valid dict (type=type_error.dict)

This happens only when the database is postgresql. When i use sqlite everything works fine.

Environment:

  • OS: Linux fortdey 5.1.15-arch1-1-ARCH #1 SMP PREEMPT Tue Jun 25 04:49:39 UTC 2019 x86_64 GNU/Linux and docker container with last Ubuntu
  • Fastapi 0.29.1
  • Python Python 3.7.3

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

14reactions
bharlingcommented, Jul 9, 2019

Use the ‘orm_mode’ flag in the pydantic schema, it’s a new thing in the latest pydantic release. See pydantic docs for details. Solved the issue for me

0reactions
seerwrightcommented, Nov 22, 2021

orm_mode = True solved it for me as well. I traced this into an await serialize_response within sqlalchemy and it was feeling awkward that I had to go there. I’m glad I Googled before pressing on, but I do want to understand exactly what orm_mode is doing to change this specific behavior at some point. Anyway, thx.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mapping issues from Sqlalchemy to Pydantic - from_orm failed
I'm trying to get my result dictonary ...
Read more >
Models - pydantic
Validation is a means to an end: building a model which conforms to the types and constraints provided. In other words, pydantic guarantees...
Read more >
Handling Validation Errors - python-jsonschema
When an invalid instance is encountered, a ValidationError will be raised or returned, depending on which method or function is used.
Read more >
Cool Things You Can Do With Pydantic - Medium
Pydantic models. Pydantic is a useful library for data parsing and validation. It coerces input types to the declared type (using type ...
Read more >
Handling Application Errors — Flask Documentation (2.2.x)
The YOUR_DSN_HERE value needs to be replaced with the DSN value you get from your ... start with the correct headers and status...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found