mattrweaver 0 Newbie Poster

I am trying to delete files in flask after they are downloaded, but I'm hung up on file path issues, generating empty excel files.

The file that is downloaded is passed to the route for the file download from a session variable. The following code finds the file and downloads it:

@app.route('/dnld_outputfile/', methods=['POST','GET'])
def download_output(): 
    output_file1 = session.get('session_variable', None)
    return send_file(output_file1, attachment_filename='outputfile.xlsx', as_attachment=True)

But this code uses a generator to serve and then delete the file:

@app.route('/dnld_outputfile/', methods=['POST','GET'])
def download_output(): 
    output_file1 = session.get('output_file', None)
    path = os.path.join(current_app.instance_path,output_file1)
    def generate():
        with open(path) as f:
            yield from f
        os.remove(output_file1)
    r = app.response_class(generate(), mimetype='text/xlsx')
    r.headers.set('Content-Disposition', 'attachment', filename='outputfile1.xlsx')
    return r 

I have tried absolute paths to the folder where the downloaded files are stored instead of "current_app.instance_path", but cannot connect to the files.

Can anyone help me sort out what's wrong?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.