Forward image file with Flask middleware

97 Views Asked by At

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

There are 1 best solutions below

0
Pavel Kříž On

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) )