1

I trying to delete a file I've created after it was displayed on the webservice. However with the current placement of the function, it says 'remove_file(response) is not accessed' and when I run the webservice I get an error when outputting the file, as it apparently already has been deleted.

I don't know what to do anymore, I've tried placing the afer_this_request function right after the upload_file declaration, after the return render template, all of it never works. I'm going crazy, so any help would make my year!

    @app.route('/', methods=['POST', 'GET'])
    def upload_file():
        if request.method == 'POST':
            myuuid = uuid.uuid4()
            # check if the post request has the file part
            if 'file' not in request.files:
                return render_template('error.html')
            file = request.files['file']
            # If the user does not select a file, the browser submits an
            # empty file without a filename.
            if file.filename == '':
                return render_template('error.html')
    
            if file and allowed_file(file.filename):
                sfilename = secure_filename(file.filename)
                if not os.path.exists(app.config['UPLOAD_FOLDER']):
                    os.mkdir(app.config['UPLOAD_FOLDER'])
                output_path = os.path.join(app.config['UPLOAD_FOLDER'], sfilename)
                file.save(output_path)
    
       
                if 'Alpha Miner' in request.form:
                    Alpha(pro_file, myuuid)
                    img_url = url_for('static', filename=str(myuuid) + '.gv.svg')
    
                    @after_this_request
                    def remove_file(response):
                        os.remove(img_url)
                        return response
                  
                    titel = "Petri Net for Alpha Miner: " + sfilename    
                    return render_template('upload.html', img_url=img_url, titel = title)
icbidt1018
  • 23
  • 5
  • it isn't? I imported it with flask: https://flask.palletsprojects.com/en/2.0.x/api/#flask.after_this_request – icbidt1018 Oct 31 '21 at 21:09

1 Answers1

-1

Try this :

file_handle = open(img_url, 'r')
@after_this_request
    def remove_file(response):
        try:
            os.remove(img_url)
            file_handle.close()
        except Exception as error:
            app.logger.error("Error removing or closing downloaded file handle", error)
        return response
  • doesn't work sadly :( when i put file_handle or img_url into the render template as parameter, I still get a filenotfound error – icbidt1018 Oct 31 '21 at 21:25
  • please have a look at this: https://stackoverflow.com/questions/24612366/delete-an-uploaded-file-after-downloading-it-from-flask , there is a good answer in this link, i hope it helps you – saeedhosseini Oct 31 '21 at 21:29
  • recommed you read the "Stream file, then delete" part @icbidt1018 – saeedhosseini Oct 31 '21 at 21:30