在Django长时间轮询 [英] Long polling in Django

查看:166
本文介绍了在Django长时间轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django应用程序中使用了一种长时间的轮询,以便在客户端进行时将有关长操作的状态消息返回给客户端。我通过在我的视图函数中返回一个HttpResponse对象来实现,该对象使用返回字符串的迭代器初始化。这一切都很好,但是迭代器函数变得很长,收益率很高,可以返回状态消息。

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"

。 ..我想要:

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,但似乎并没有完全烘烤(尤其是在浏览器支持方面)。我也考虑过服务器的真正轮询,但是会更复杂,所以我想继续保持打开的连接和流传输消息。

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.

推荐答案

尝试:

import itertools

def my_long_operation():
    return itertools.chain(do_something(), do_something_else())

这篇关于在Django长时间轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆