【问题标题】:django StreamingHttpResponse - catch exception raised in streaming_content iteratordjango StreamingHttpResponse - 捕获流内容迭代器中引发的异常
【发布时间】:2017-11-08 16:32:18
【问题描述】:

我正在尝试在返回 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 子句永远不会到达。

谢谢

【问题讨论】:

    标签: python django iterator django-views chunked


    【解决方案1】:

    早在reportgen_iterator 中的异常引发之前,您就已从get 方法返回。

    这是为什么呢?

    应该给它一个生成字符串作为内容的迭代器。你 无法访问其内容,除非通过迭代响应对象 本身。这应该只发生在响应返回到 客户。

    视图函数与迭代器(在您的情况下为生成器)一起返回,但当您仍在函数内部时,它并没有完全迭代。这就是为什么在 get 方法中从未捕获到异常的原因。

    https://docs.djangoproject.com/en/1.11/ref/request-response/#streaminghttpresponse-objects

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      相关资源
      最近更新 更多