我试着写一个解决方案(不是百分之百确定这样的投票真的有必要)。当然,html+js必须移动到真正的html/js文件中,但这里我将它保持为一个小示例:
from bottle import get, run, request, static_file
import time
from threading import Thread
import os
def dothejob(i):
time.sleep(5) # the file takes 5 to 60 seconds to be prepared
with open('test.txt', 'w') as f:
f.write('Hello')
@get('/')
def static(filename):
return static_file(filename, root='.', download=True)
@get('/isready')
def isready():
return '1' if os.path.exists('test.txt') else '0'
@get('/')
def generatefile():
i = request.params.get('id', '', type=str)
thread = Thread(target=dothejob, args=(i, ))
thread.start()
return """Your file is being prepared. Please wait 5 seconds (do not reload the page)...
poll = function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/isready');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
if (xhr.responseText == 1)
document.write('Your file is now ready: download link');
else
setTimeout(poll, 1000);
}
}
xhr.send(null);
}
setTimeout(poll, 1000);
"""
run(host='0.0.0.0', port=80, debug=True, quiet=True)