Search code examples
pythoncherrypy

How to serve file with cherrypy and delete the file from server?


I need to create a file on the server, serve it to the client, and I would prefer to delete the file from the server afterwards.

Here's what I'm currently trying:

def myaction():
    fs = facts.generatefacts(int(low),int(high),int(amount),op)
    filename = 'test.txt'
    FILE = open(filename,'w')
    FILE.writelines('my\nstuff\nhere')
    FILE.close()
    RETURN_FILE = open(filename,'r')
    return serve_fileobj(RETURN_FILE,disposition='attachment',
                         content_type='.txt',name=filename)

myaction.exposed = True

There are several things about this that I don't like. I wouldn't think that I would have to open the file twice, for example. I would expect that there is a way to write content directly to the response object, without ever creating a file object, but that isn't my question today.

The above code accomplishes what I want, but leaves a file behind. If I delete the file before returning the response, then (of course) the file isn't found.

Is there a way to remove this file as soon as it has been served?

I'm coming from the Java world, so I'm a bit disoriented, and any other suggestions to improve the above are appreciated.


Solution

  • 1) You can move file to temporary folder and remove all files older 0.5 hours

    2) You can try

    result = serve_fileobj(RETURN_FILE,disposition='attachment',
                             content_type='.txt',name=filename)
    os.unlink(filename)
    return result
    

    3) Try to use StringIO file object that can wrap string to look like a file.