django流字典多次而不破坏JSON [英] django stream a dictionary multiple times w/o breaking JSON

查看:110
本文介绍了django流字典多次而不破坏JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Django流式传输响应.为此, 我有这样的看法:

I want to stream a response using Django. In order to do so, I have a view like this:

def flights(request, query): req_obj = Flights.RequestObject(query) return StreamingHttpResponse(req_obj.make_response(), content_type="application/json")

def flights(request, query): req_obj = Flights.RequestObject(query) return StreamingHttpResponse(req_obj.make_response(), content_type="application/json")

为了生成流的数据,我有一个生成器函数"make_response", 这是类航班"的一种方法,实例化为"req_obj".

In order to produce the data for the stream, I have a generator function "make_response", which is a method of the class "Flights", instantiated as "req_obj".

生成器函数在特定时刻产生一个纯python字典.

The generator function yields, at particular moments, a pure python dictionary.

def make_response(self):
   for _ in range(0,3):
      yield some_dict
      time.sleep(1)

这导致以下行为:

  • 第一次生成后,json内容返回有效;
  • 第二次(及之后)产生后,返回的json内容无效;

如果返回的字典是这样的

if the dictionary returned is something like this

{数据":"some_data"}

{"data": "some_data"}

, 在第二次收益率之后,用户收到的响应是:

, after the second yield, the response the user receives is:

{数据":"some_data"} {数据":"some_data"}

{"data": "some_data"}{"data": "some_data"}

,它不是有效的json.

, which is NOT valid json.

关于如何解决此问题的任何建议?

Any suggestions on how to solve this problem?

推荐答案

您是否尝试过类似

req_obj.update(req_obj.make_response())

这将使用您的方法新产生的值更新您的初始字典吗?

which will update your initial dict with the values newly yielded from your method?

这篇关于django流字典多次而不破坏JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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