Best way to serve file to html page once in flask (python)

for a assignment we need to make a website with flask or django as backend. I’ve been working on it and am almost finished but am running into a problem that I cannot really seem to tackle. I have users submit photo’s to the website via either a url or upload. I will do some stuff to the images and than want to display the image again. But after the users closes the page where is image is being show I’d like for the image to be automatically deleted from my server.

I was thinking about making a temporary file, but from what I gather these only get deleted once the file is closed. But since I have to return the template with flask first I cannot really close it then right? What would be the best way to approach this?

Answer

After the user receives the file, you can safely delete it and it’ll still be in their browser. Since you can’t remove it after returning from the function, you must first load it into memory with a variable, then remove the file, and then return the image you have loaded. This example does just that:

from flask import Flask, send_file
import io
import os
app = Flask(__name__)

@app.route("/image-route.jpg")  # Change this to match your route
def send_my_image():
    image_in_memory = None  # Create variable so it has the correct scope
    # Open file and load it into a BytesIO object which behaves just as if it was a file
    with open('my-file-location.jpg', 'rb') as f:
        image_in_memory = io.BytesIO(f.read())
    # Since we have the image in memory, we can safely remove it
    os.remove('my-file-location.jpg')  
    # Finally, return our BytesIO object as if it was a file
    return send_file(image_in_memory, attachment_filename='my-file.jpg')

app.run()

Leave a Reply

Your email address will not be published. Required fields are marked *