skip to Main Content

So I am trying to make a request on the route:

http://127.0.0.1:8000/testadmins
with the folowing function:

@app.get("/testadmins/")
async def get_admins():
    return await get_database()

get_database() is this:

async def get_database():
    uri = "(my mongo uri)"
    client = MongoClient(uri, server_api=ServerApi('1'))
    adms = client.test['admins'].find()
    print(adms)
    
    return adms

The function should return all the admins in that collection.

if I print the admins to the console they are shown, but the route wont return them.
i get this error:
TypeError(‘vars() argument must have dict attribute’)]

I tried adding async await everywhere, i tried wrapping the function in fastApi’s json_encodable()
but nothing.

If I try to make the request in Postman it returns 500 ( internal server error ).

what should I do?

( update: i think it has to do with the date and time as it tried only one key at a time multiple times and only those that had a value stored as a datetime.datetime(…) format didnt work.

( __v and _id didnt work either but idk )

Traceback:

Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/encoders.py", line 235, in jsonable_encoder
    data = vars(obj)
           ^^^^^^^^^
TypeError: vars() argument must have __dict__ attribute

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 426, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/applications.py", line 289, in __call__
    await super().__call__(scope, receive, send)
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/applications.py", line 122, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/middleware/errors.py", line 184, in __call__
    raise exc
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/middleware/errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
    raise exc
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
    await self.app(scope, receive, sender)
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__
    raise e
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__
    await self.app(scope, receive, send)
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/routing.py", line 718, in __call__
    await route.handle(scope, receive, send)
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/routing.py", line 276, in handle
    await self.app(scope, receive, send)
  File "/opt/homebrew/lib/python3.11/site-packages/starlette/routing.py", line 66, in app
    response = await func(request)
               ^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/routing.py", line 291, in app
    content = await serialize_response(
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/routing.py", line 179, in serialize_response
    return jsonable_encoder(response_content)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/encoders.py", line 209, in jsonable_encoder
    jsonable_encoder(
  File "/opt/homebrew/lib/python3.11/site-packages/fastapi/encoders.py", line 238, in jsonable_encoder
    raise ValueError(errors) from e
ValueError: [TypeError("'ObjectId' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]

2

Answers


  1. Chosen as BEST ANSWER

    **I solved the Object Id problem with the following: **

    document['_id'] = str(document['_id'])
    

    I just transformed it into a string and now it works.

    also I removed some other function calls, added some params, anyways, here s the whole code:

    db = MongoClient(uri)
    
        result = []
        collection = db.test[collection_name].find()
    
        for document in collection:
            # Convert ObjectId to string
            document['_id'] = str(document['_id'])
            result.append(document)
    
        return result
    

  2. you should modify

    async def get_database():
        uri = "(my mongo uri)"
        client = MongoClient(uri, server_api=ServerApi('1'))
        adms = []
        cursor = client.test['admins'].find()
        for document in cursor:
            document.pop('ObjectId')
            adms.append(document)
        return adms
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search