使用Django串流JSON的正确方法 [英] Proper way of streaming JSON with Django

查看:34
本文介绍了使用Django串流JSON的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web服务,该服务获取用户请求并为此请求生成(多个)解决方案.我想尽快返回解决方案,并在准备好后发送其余解决方案.

为了做到这一点,我考虑过使用Django的Http流响应.不幸的是,由于下面将要描述的问题,我不确定这是否是最合适的方法.

我有一个Django视图,该视图接收查询并通过流响应进行回答.该流返回由生成器返回的数据,该生成器始终是python字典.问题在于,在流的第二次返回操作中,Json内容中断.

如果用作响应的python词典类似于{key:val},则在第二个收益率之后,返回的响应为{key:val} {key:val},这是无效的Json.

关于如何在不同时间返回多个Json对象的任何建议吗?

解决方案

尝试使用类似的方法进行解码例如

导入json

json.dumps({key:val} {key:val},spacers =('}',':'))#检查它

i have a webservice which gets user requests and produces (multiple) solution(s) to this request. I want to return a solution as soon as possible, and send the remaining solutions when they are ready.

In order to do this, I thought about using Django's Http stream response. Unfortunately, I am not sure if this is the most adequate way of doing so, because of the problem I will describe below.

I have a Django view, which receives a query and answers with a stream response. This stream returns the data returned by a generator, which is always a python dictionary. The problem is that upon the second return action of the stream, the Json content breaks.

If the python dictionary, which serves as a response, is something like {key: val}, after the second yield the returned response is {key: val} {key: val}, which is not valid Json.

Any suggestions on how to return multiple Json objects at different moments in time?

解决方案

Try decoding with something like for example

import json

json.dumps( {key: val} {key: val}, separators=('}', ':')) #check it

这篇关于使用Django串流JSON的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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