[英]python flask response using jsonify
使用flask API構建的兩個應用程序嘗試接收具有巨大JSON響應的響應失敗,錯誤10054,“現有連接被遠程主機強行關閉”
我可以縮小這個問題,即當響應很大時,它會失敗
@api.route('/endpoint', methods=['POST'])
def endpoint():
result = {small / huge dict}
return jsonify({'result': result}), 200
來電方:
result = requests.post(url, params=data['args'], json=data['payload'])
return result.json()['result']
錯誤日志:
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
更新:
試圖產生響應作為計划文本和失敗更少,但仍然偶爾出現問題。
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
作為錯誤日志,問題可能是以下之一:
請求返回字節,需要解碼或Json解碼失敗。 我建議你應該改變代碼如下:
result = requests.post(url, params=data['args'], json=data['payload']).text
return result
如果你需要使用json,你應該使用:
result = json.loads(requests.post(url, params=data['args'], json=data['payload']).text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.