If you are using Linux or another Unix-like OS, you can exploit the fact, that, when when you delete a file that is kept open (static_file
does that), the file vanishes from the directory but the real deletion is delayed by the OS until the file is no longer open. That means that you don't need to wait for the file to be 100% downloaded.
@post('/download')
def downloadpage():
f = static_file('tempDS6529QSGYUA41.csv', root='temp', download=True)
os.remove('tempDS6529QSGYUA41.csv')
return f
or (performing the action even if an error happens while opening the file):
@post('/download')
def downloadpage():
try:
return static_file('tempDS6529QSGYUA41.csv', root='temp', download=True)
finally:
os.remove('tempDS6529QSGYUA41.csv')
If you want to perform the action only and exactly when it was 100 % downloaded, something like this should work (ignoring some corner cases):
@post('/download')
def downloadpage():
# Ignore partial download request that would confuse our code
if 'HTTP_RANGE' in request.environ:
del request.environ['HTTP_RANGE']
def wrapper_iterator(f):
for chunk in WSGIFileWrapper(f):
yield f
os.remove('tempDS6529QSGYUA41.csv')
f = static_file('tempDS6529QSGYUA41.csv', root='temp', download=True)
return wrapper_iterator(f)