我试图在返回StreamingHttpResponse时处理错误:
不会捕获作为straeming_content使用的迭代器中手动引发的异常。
下面是代码:
def reportgen_iterator(request, object_id):
output_format = request.GET.get('output', 'pdf')
debug_mode = request.GET.get('debug', False)
response_data = {
'progress': 'Retrieving data...',
}
# code....
yield json.dumps(response_data)
# code ...
raise Exception('bla bla') # manually raised exception
# other code ......
yield json.dumps(response_data)
class StreamingView(View):
def get(self, request, object_id):
"""
"""
stream = reportgen_iterator(request, object_id)
try:
response = StreamingHttpResponse(
streaming_content=stream, status=200,
content_type='application/octet-stream'
)
response['Cache-Control'] = 'no-cache'
return response
except Exception as e:
# exception not catched
return HttpResponseServerError(e.message)对如何正确处理这件事有什么帮助吗?从未触及except子句。
谢谢
发布于 2017-06-07 14:24:32
在引发get中的异常之前很久,您就已经从reportgen_iterator方法返回。
为什么会这样呢?
应该给它一个迭代器,它生成字符串作为内容。您不能访问它的内容,除非迭代响应对象本身。只有当响应返回给客户端时,才会发生这种情况。
视图函数返回迭代器(在您的例子中是生成器),但是当您仍然在函数中时,它不会被完全迭代。这就是为什么在get方法中从未捕获异常的原因。
https://docs.djangoproject.com/en/1.11/ref/request-response/#streaminghttpresponse-objects
https://stackoverflow.com/questions/44410653
复制相似问题