0

I have been following the advice given on this thread: How to pass image to requests.post in python?

However, I got stuck with the error, "ValueError: read of closed file".

I have been trying to invoke an API that does some image recognition. At the moment, I am using Postman's form-data feature to send it to the Django server, which then uses "requests" to invoke the API. Let me show you the code snippet.

def post(self, request):

    img = request.FILES["file"]
    with img.open("rb") as f:
        files = {"fileToUpload": f}
    url = "http://XXXXXXXXXXXXXXXX/getSimilarProducts?APIKEY=XXXXXXX"
    response = requests.post(url, files=files)

After sending the request, when I check each variable with the debugger, the 'img' variable contains a temporary uploaded file like so:

<TemporaryUploadedFile: XXXXXXXXXXXXXX.png (image/png)>

What am I missing? And what should I do to overcome this error? Thanks a lot in advance!

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
Nicholas An
  • 156
  • 1
  • 9

1 Answers1

1

the response should be within the with context

def post(self, request):
    img = request.FILES['file']
    with img.open('rb') as f:
        files = {'fileToUpload': f}
        url = 'http://XXXXXXXXXXXXXXXX/getSimilarProducts?APIKEY=XXXXXXX'
        response = requests.post(url, files=files)
JPG
  • 82,442
  • 19
  • 127
  • 206