简体   繁体   English

使用 Django 传输 JSON 的正确方法

[英]Proper way of streaming JSON with Django

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.为了做到这一点,我想到了使用 Django 的 Http 流响应。 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.我有一个 Django 视图,它通过流响应接收查询和答案。 This stream returns the data returned by a generator, which is always a python dictionary.该流返回生成器返回的数据,生成器始终是一个 Python 字典。 The problem is that upon the second return action of the stream, the Json content breaks.问题在于,在流的第二个返回操作中,Json 内容会中断。

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.如果作为响应的python 字典类似于{key: val},则在第二个yield 之后返回的响应是{key: val} {key: val},这不是有效的Json。

Any suggestions on how to return multiple Json objects at different moments in time?关于如何在不同时间及时返回多个 Json 对象的任何建议?

Try decoding with something like for example尝试用类似的东西解码

import json导入json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM