Django 中的长轮询
我在 Django 应用程序中使用一种长轮询,以便在操作进行时向客户端返回有关长操作的状态消息。我通过在视图函数中返回一个 HttpResponse 对象来实现此目的,该对象是使用返回字符串的迭代器初始化的。这一切都很好,但是迭代器函数变得相当长,需要大量的收益来返回状态消息。
我想通过将长操作分成多个函数来更好地构建它,每个函数都返回自己的状态消息。但我看不出有什么办法可以做到这一点。换句话说,我有这个:
def my_long_operation():
do_something()
yield "Did something"
do_something_else()
yield "Did something else"
...并且我想有:
def do_something():
do_first_part_of_something()
yield "Did first part of something"
do_second_part_of_something()
yield "Did second party of something"
def do_something_else():
do_first_part_of_something_else()
yield "Did first part of something else"
do_second_part_of_something_else ()
yield "Did second party of something else"
def my_long_operation():
do_something()
do_something_else()
有没有某种方法可以获取第二个示例中的收益,以便为迭代器的调用者产生值?如果没有,有更好的方法吗?我研究了 WebSockets,但它似乎还没有完全成熟(特别是在浏览器支持方面)。我还考虑了对服务器的实际轮询,但这会复杂得多,因此我想继续保持开放连接并在可能的情况下传输消息。
I'm using a sort of long polling in my Django app to return status messages about a long operation to the client as it progresses. I do this by returning an HttpResponse object in my view function that is initialized with an iterator that returns strings. This all works great, but the iterator function is getting pretty long with tons of yields to return the status messages.
I'd like to architect this better by splitting the long operation into multiple functions, each of which returns its own status messages. But I can't see a way to do this. In other words, I have this:
def my_long_operation():
do_something()
yield "Did something"
do_something_else()
yield "Did something else"
...and I'd like to have:
def do_something():
do_first_part_of_something()
yield "Did first part of something"
do_second_part_of_something()
yield "Did second party of something"
def do_something_else():
do_first_part_of_something_else()
yield "Did first part of something else"
do_second_part_of_something_else ()
yield "Did second party of something else"
def my_long_operation():
do_something()
do_something_else()
Is there some way to get the yields in the second example to yield values to the caller of iterator? If not, is there a better approach? I looked at WebSockets but it doesn't seem to be fully baked yet (especially in terms of browser support). I also considered real polling of the server but that will be much more complex, so I'd like to continue to keep the open connection and stream messages across if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
Try: