【问题标题】:How to implement "Your file is being prepared. Please wait 1 minute." that auto-updates when the file is ready with Python Bottle?如何实现“您的文件正在准备中。请等待 1 分钟。”当文件准备好 Python Bottle 时自动更新?
【发布时间】:2018-11-29 09:59:46
【问题描述】:

我想做一个 “您的文件正在准备中。请等待 1 分钟。” 页面通过让客户端在文件准备好时下载文件来自动更新。

显然,这是行不通的:

from bottle import route, post, get, run, request, view, static_file, redirect
import time
from threading import Thread

def dothejob(i):
    time.sleep(10)  # the file takes 5 to 60 seconds to be prepared
    with open('test.txt', 'w') as f:
        f.write('Hello')
    return static_file('test.txt', root='.', download=True)  # error here

@get('/generatefile')
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 1 minute."

run(host='0.0.0.0', port=80, debug=True, quiet=True)

因为当dothejob 返回时,HTTP 请求不再存在:

RuntimeError: 请求上下文未初始化。

当文件在服务器上准备好时,如何正确地做这样一个自动更新页面?

注意:

  • 我想在这里避免使用websockets(我已经将它用于更复杂的项目:聊天等,它有时在某些不接受它的连接上不起作用+其他原因此处的主题)并寻求最简单的解决方案。

  • 我想知道它是否真的需要像 Update and render a value from Flask periodicallyanswer 这样的 AJAX 轮询,或者是否有更简单的解决方案。

【问题讨论】:

  • 顺便说一句:你真的不想在一个线程中做真正的后台工作。使用像 Celery 或 RabbitMQ 这样的队列。
  • @JonathonReinhart 是的,我只是用它来做一个简单的小例子,但在现实生活中,我会使用像 Celery 这样的东西。

标签: python multithreading asynchronous bottle


【解决方案1】:

我试图写一个解决方案(不是 100% 确定这样的轮询真的有必要)。当然 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('/<filename>')
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)...
<script>
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: <a href="/test.txt">download link</a>');
            else
                setTimeout(poll, 1000);
        }
    }
    xhr.send(null);
}

setTimeout(poll, 1000);
</script>
"""    

run(host='0.0.0.0', port=80, debug=True, quiet=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多