2

I have a Flask backend which generates an image based on some user input, and sends this image to the client side using the send_file() function of Flask.

This is the Python server code:

@app.route('/image',methods=['POST'])
def generate_image():
    cont = request.get_json()
    t=cont['text']
    print(cont['text'])
    name = pic.create_image(t) //A different function which generates the image
    time.sleep(0.5)
    return send_file(f"{name}.png",as_attachment=True,mimetype="image/png")

I want to delete this image from the server after it has been sent to the client.

How do I achieve it?

RishiC
  • 768
  • 1
  • 10
  • 34

3 Answers3

6

Ok I solved it. I used the @app.after_request and used an if condition to check the endpoint,and then deleted the image

@app.after_request
def delete_image(response):
    global image_name
    if request.endpoint=="generate_image": //this is the endpoint at which the image gets generated
        os.remove(image_name)
    return response
RishiC
  • 768
  • 1
  • 10
  • 34
2

Another way would be to include the decorator in the route. Thus, you do not need to check for the endpoint. Just import after_this_request from the flask lib.

from flask import after_this_request


@app.route('/image',methods=['POST'])
def generate_image():
    @after_this_request
    def delete_image(response):
        try:
            os.remove(image_name)
        except Exception as ex:
            print(ex)
        return response

    cont = request.get_json()
    t=cont['text']
    print(cont['text'])
    name = pic.create_image(t) //A different function which generates the image
    time.sleep(0.5)
    return send_file(f"{name}.png",as_attachment=True,mimetype="image/png")
rockstaedt
  • 61
  • 3
  • Thanks! Is this a new function added to Flask? During the time the original post was created, I couldn't find this – RishiC Aug 15 '22 at 09:49
  • Apparently, this was introduced in Flask 0.9, see the [documentation](https://flask.palletsprojects.com/en/1.0.x/api/#flask.after_this_request) :) – rockstaedt Aug 16 '22 at 10:17
  • Hii, I am using the same method, but it's saying that the file is being accessed by another process, any help on that? – Ishan Sahu Jan 13 '23 at 06:38
  • Mhm… do you see which process it is? Is it a file you preprocessed in python? Then, I would check if you closed the file. – rockstaedt Jan 14 '23 at 07:26
-1

You could have another function delete_image() and call it at the bottom of the generate_image() function

  • 2
    The `return send_file(...)` statement exits the generate_image function, so can't add anything below that – RishiC Jun 20 '20 at 09:20