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.

Can't return dictionary as response when values are numpy arrays

See original GitHub issue
from backend import Model
from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()
model = Model()

@app.get("/")
def read_root():
    return {"Hello World"}

@app.post("/enroll")
def enroll_user(uploadedfile: UploadFile = File(...), username: str = Form(...)):
    model.enroll(uploadedfile.file, username)
    return "success"

@app.get("/db")
def view_db():
    return model._database

Description

  • I receive an uploaded audio file and a username and pass them to model.enroll to generate an embedding for that file and store it in the dictionary _database as `{username: embedding}.
  • Embedding is of type numpy.ndarray and of shape (1, 512).
  • The problem arises when I try and hit the /db endpoint to view the _database variable, it works when the dictionary is still empty but when it is populated it throws back this error ValueError: [ValueError('dictionary update sequence element #0 has length 512; 2 is required'), TypeError('vars() argument must have __dict__ attribute')].
  • The error seems to arise from fastapi/encoders line 139.
  • I tried populating the dictionary with all sorts of sequences and it worked just fine.
  • The expected return is {username: embedding}.

Environment

  • OS: Linux
  • FastAPI Version: 0.61.1
  • Python version: 3.8.2

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
Mausecommented, Oct 5, 2020

It looks like fastapi is trying to fall back to converting the numpy array to a dict using vars as it doesn’t know what to do with it. You are probably best off converting the array into a python list yourself before returning it.

@app.get("/db")
def view_db():
    return {username: embedding.tolist() for username, embedding in model._database.items()}
0reactions
tiangolocommented, Nov 9, 2022

Thanks for the help everyone! ☕

And thanks for coming back to close the issue @kareemamrr 🍰

Sorry for the long delay! 🙈 I wanted to personally address each issue/PR and they piled up through time, but now I’m checking each one in order.

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI: How to return a dictionary that includes numpy arrays?
You can do this by using the custom Response objects in FastAPI. return Response(content=numpy_as_json, media_type="application/json"). Or if ...
Read more >
Python Serialize NumPy ndarray into JSON - PYnative
In this article, I will show you how to make NumPy array JSON serializable so that you can convert any NumPy array into...
Read more >
Python Read JSON File – How to Load ... - freeCodeCamp
loads(data_JSON) creates a new dictionary with the key-value pairs of the JSON string and it returns this new dictionary. Then, the dictionary ......
Read more >
Python KeyError Exceptions and How to Handle Them
This operator will return a Boolean ( True or False ) value indicating whether the key is found in the dictionary. In this...
Read more >
Structured arrays — NumPy v1.23 Manual
The keys of the dictionary are the field names and the values are tuples ... Structured arrays with a different number of fields...
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