0

I am creating an app where I have a middleware (Flask) inbetween a client Flutter app and a image provider (Flask). I would like to get images to the Flutter app from the image provider trough the middleware. The middleware is public as an API and so is the image provider. My idea what I want is visualised in following diagram:
enter image description here I dont know how to implement the middlewere part, my current implementation of the middleware is following:

# simplified version of my code in minimal form
@image_bp.route('/image/<id>', methods=['GET'])
def get_dataset_image(id):
    res = requests.get(f'{IMAGE_PROVIDER_URL}/image/{id}')
    return res.raw.read(), res.status_code, res.headers.items()

The image provider is then implemented as follows (I used this code before to send images directly):

# simplified version of my code in minimal form
@image_bp.route('/image/<id>', methods=['GET'])
def get_dataset_image(id, image):
    image_path = images[id]
    return send_file(image_path, mimetype='image/jpg'), 200

To solve my middleware problems I have tried some naive approach and also a code like this following one (didnt help):

# simplified version of the code in minimal form
res = requests.get(url, allow_redirects=True)

return send_file(
  io.BytesIO(res.content),
  download_name='image.jpg',
  mimetype='image/jpg'
  )

It is an answer from this Stack Overflow question. I have also another Stack Overflow questions answer from which I created my code. It is not working for me as well.

Could you please help me on how to do it? I would be grateful not only for full answer but also for any hints.

  • 1
    To use the raw socket response like in your first approach, the `stream` attribute needs to be set to `True`. See [here](https://requests.readthedocs.io/en/latest/user/quickstart/#raw-response-content) for the documentation. – Detlef Apr 02 '23 at 22:30
  • Oh I see, thank you. There is response.raw and response.content without deducing the encoding. I used the latter, because it is used in context with images in the linked documentation and it works fine, I am going to try the raw later, but I have suspicions that it is the same, isnt it? – Pavel Kříž Apr 05 '23 at 09:23
  • 1
    I would prefer the first version as it is more like a proxy. You pass all the data from the image provider directly through to the client. My guess is also that the second solution requires more memory. – Detlef Apr 05 '23 at 11:32

1 Answers1

0

Working solution

I have solved it with following solution (returning response created with the Response constructor should be equivalent to returing the elements like a touple)

# simplified version of my code in minimal form
@image_bp.route('/image/<id>', methods=['GET'])
def get_dataset_image(id):
    res = requests.get(f'{IMAGE_PROVIDER_URL}/image/{id}', stream=True)
    return Response( res.content, headers=dict(res.headers) )