0

I have a Flask application running in python. There is a client that is serving images from disk. I would like a server to hit an end point and retrieve the images.

On the client's side:

@app.route('/api/get_image')
def get(self, id):
   # Map id to filename.
   return send_file(filename)

This works when I call the client's end point from a browser.

On the server side, I have a similar function that should call the above endpoint.

@app.route('/api/get_image')
def get(self, id):
    return requests.get(client_url + '/api/get_image')

When I call the server endpoint, I get:

TypeError: <Response [200]> is not JSON serializable

But it doesn't work even if I try .json(). How do I return the image payload?

trycatch22
  • 307
  • 4
  • 14
  • Does this answer your question? [How to download image using requests](https://stackoverflow.com/questions/13137817/how-to-download-image-using-requests) – ti7 Mar 04 '21 at 23:31

1 Answers1

0

Don't return the object from requests.get() directly, instead retrieve the .raw or .content object from it

r = requests.get(url)
r.raise_for_status()  # raise an Exception if the request failed
return r.content
ti7
  • 16,375
  • 6
  • 40
  • 68
  • r.raw returns: TypeError: is not JSON serializable and r.content throws a bunch of hex numbers followed by is not JSON serializable – trycatch22 Mar 04 '21 at 23:45
  • Can you draw a diagram of your setup? it sounds like you're trying not to consume the response, but to reserialize it to JSON and pass it to a client?.. perhaps your setup is like server1 (has image) -> server2 -> client (asks for JSON) .. in this case, you'll likely need to compress and base64 the image (to allow you to send it as text to the client in a JSON structure) – ti7 Mar 04 '21 at 23:50
  • I want the behavior the client has...when I hit its end point from a browser, I can view the image. Right now, what I am trying to do is: browser -> server1 end point -> server2 end point I am not interested in the JSON response. I want to be able to view the image in the browser the way I am able to from hitting the client's end point. – trycatch22 Mar 04 '21 at 23:52
  • The problem is likely some brand of when you `return` from the `get` method, Flask does more than you're expecting (consider: **where is the function returning to?**) – ti7 Mar 05 '21 at 00:02
  • FLASK's API documentation didn't give me much info about the `return` details of `send_file`. It is a `Response` object. I am unclear how to match this object from the higher function call to the browser higher up when `get` is invoked. – trycatch22 Mar 05 '21 at 00:07