FastAPI Multiple file uploads: Getting content of multiple images works but unable to do any processing on them

Viewed 316

I am new to FastAPI and have been trying to access content(in Colab) from multiple image files(all with extension .jpg) that have been uploaded through Postman.

While I am able to successfully get the content, at times I am unable to do any processing on them. I am trying to print the shape of the image but it doesn't work.

Currently, my code is as follows-

IMAGEDIR = "/content/fastapi-images/"
img_path = os.listdir(IMAGEDIR)

@app.post("/imgspost")
async def post_num_new(files: List[UploadFile] = File(...)):
  for file in files:      #This for loop works as I am able to see the files being saved in the folder
    
    contents  = await file.read()

    # Writing the contents of the file into the folder
    with open(f"{IMAGEDIR}{file.filename}", "wb") as f:
      f.write(contents)
  
  for img in img_path:  # Works sometimes. Sometimes it doesn't work
    print(img)
    if img.endswith('.jpg'):
      print("True")
      testim = cv2.imread(IMAGEDIR + img)
      numpyimg = np.array(testim)

      print(numpyimg.shape)

  return {"filenames": [file.filename for file in files]} # Returns filenames successfully at all times


The logic runs without any errors. The first for loop works well. I am able to see and access the image files on colab. The second for loop, however, only works sometimes and at times it doesn't(does not print anything).

There doesn't seem to be any pattern to it working or not working.

Things that I have tried but has been unsuccessful -

  1. Changed the function type from async to sync(by removing the async keyword)
  2. Tried 'contents = file.read()' instead of 'contents = await file.read()'
  3. Tried closing the file operator f after reading all the files

I am also attaching the screenshot of the messages I get on the server. Currently- Current output Ideal output - Ideal output

I would be extremely grateful to anyone who can help me identify where I might be going wrong!

0 Answers
Related