简体   繁体   English

使用jsonify的python flask响应

[英]python flask response using jsonify

Two applications built with flask API, trying to receive a response with huge JSON response fails with Error 10054, 'An existing connection was forcibly closed by the remote host' 使用flask API构建的两个应用程序尝试接收具有巨大JSON响应的响应失败,错误10054,“现有连接被远程主机强行关闭”

I could narrow the issue that when response is huge it fails 我可以缩小这个问题,即当响应很大时,它会失败

@api.route('/endpoint', methods=['POST'])
def endpoint():

   result = {small / huge dict}

   return jsonify({'result': result}), 200

caller side: 来电方:

result = requests.post(url, params=data['args'], json=data['payload'])
        return result.json()['result']

Error log: 错误日志:

File "C:\Program Files (x86)\Python36-32\lib\http\client.py", line 1331, in getresponse
response.begin()
File "C:\Program Files (x86)\Python36-32\lib\http\client.py", line 321, in begin
self.headers = self.msg = parse_headers(self.fp)
File "C:\Program Files (x86)\Python36-32\lib\http\client.py", line 206, in parse_headers
line = fp.readline(_MAXLINE + 1)
File "C:\Program Files (x86)\Python36-32\lib\socket.py", line 586, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

Update: 更新:

tried to yield response as plan text and failures where much less, but still once in a while the issue appears. 试图产生响应作为计划文本和失败更少,但仍然偶尔出现问题。

def response(output):
    return Response(response_generator(output), mimetype='text/plain')


def response_generator(result):
    result_str = json.dumps(result)
    for row in [result_str[i:i + 1024*1024] for i in range(0, len(result_str), 1024*1024)]:
         yield row

As the Error log, the problems maybe one of below: 作为错误日志,问题可能是以下之一:

  1. You are trying to open a url twice in your code. 您正尝试在代码中打开两次网址。 I don't see the whole caller side, so i cannot say if it's true or provide any further solution for sure 我没有看到整个来电方,所以我不能说它是真的还是提供任何进一步的解决方案
  2. The request return bytes, which need to be decoded or Json decoding fail. 请求返回字节,需要解码或Json解码失败。 I suggest you should change the code as below: 我建议你应该改变代码如下:

    result = requests.post(url, params=data['args'], json=data['payload']).text return result result = requests.post(url, params=data['args'], json=data['payload']).text return result

If you need work with json, you should use: 如果你需要使用json,你应该使用:

result = json.loads(requests.post(url, params=data['args'], json=data['payload']).text)

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

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