简体   繁体   中英

Sanic Python: Delete File after sending it to a client

I'm running a Python Server with Sanic, and when a client requests a file, the server creates this file and sends it to the client. For now, I've been using middleware: @app.listener('before_server_stop') to cleanup those files when the server stops.

Obviously, this solution is not nice, and I would prefer to clean them up immediately, after sending the response with the file to the client. Is there a way to do this?

The code in question:

@app.route('/getFiles', methods=['GET'])
async def getFiles(request):
        //create file
        if os.path.isfile(id+'.txt'):
            return await response.file(id+'.txt')
            // -> best would be to delete file here 

@app.listener('before_server_stop')
//delete all files

Thanks.

You could use os.remove() to delete files

if os.path.exists(id+'.txt'):
  os.remove(id+'.txt')

Steps in your case:

1- Load/read the data file into a variable

2 - Delete the file

3 - return the variable content as a HTTP file response, check if in Sanic is something like this in Django:

response = HttpResponse(data, [content_type]='text/plain')
response['Content-Disposition'] = 'attachment; filename="myfile.txt"'
return response

Chech about content-type/MIME-type file responses

I think this is a great use case for background tasks .

async def remove_file(file_name):
    os.remove(file_name)

@app.route('/getFiles', methods=['GET'])
async def getFiles(request):
    if os.path.isfile(id+'.txt'):
        request.app.add_task(remove_file(id+'.txt'))
        return await response.file(id+'.txt')
    return response.text("Nope, no file", status=404)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM