异步处理瓶(python)异步处理

2024-04-19 04:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在瓶子文档re异步响应上找到了this示例。在

下面是稍微修改的代码:

from gevent import monkey; monkey.patch_all()

from time import sleep
from bottle import hook, response, route, run


@route('/stream')
def stream():
    yield 'START'
    sleep(3)
    yield '\nPROGRESS 1'
    sleep(3)
    yield '\nPROGRESS 2'
    sleep(3)
    yield '\nPROGRESS 3'
    sleep(3)
    yield '\nEND'

run(host='0.0.0.0', port=8080, server='gevent')

从浏览器调用此视图的工作原理如the docs

If you run this script and point your browser to http://localhost:8080/stream, you should see START, MIDDLE, and END show up one by one (rather than waiting 8 seconds to see them all at once).

我想知道如何在AJAX请求中通过Javascript处理这个问题,特别是JQuery,以便按顺序显示消息。在

有什么帮助吗?在


Tags: andrunfromimportyoustreamgeventsleep
1条回答
网友
1楼 · 发布于 2024-04-19 04:11:35

jQuery doesn't support that, but you can do that with plain XHR:

var xhr = new XMLHttpRequest()
xhr.open("GET", "/test/chunked", true)
xhr.onprogress = function () {
  console.log("PROGRESS:", xhr.responseText)
}
xhr.send()

This works in all modern browsers, including IE 10. W3C specification here.

The downside here is that xhr.responseText contains an accumulated response. You can use substring on it, but a better idea is to use the responseType attribute and use slice on an ArrayBuffer.

来源:How to write javascript in client side to receive and parse `chunked` response in time?

相关问题 更多 >