首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django StreamingHttpResponse - streaming_content迭代器中引发的捕获异常

django StreamingHttpResponse - streaming_content迭代器中引发的捕获异常
EN

Stack Overflow用户
提问于 2017-06-07 10:53:58
回答 1查看 996关注 0票数 1

我试图在返回StreamingHttpResponse时处理错误:

不会捕获作为straeming_content使用的迭代器中手动引发的异常。

下面是代码:

代码语言:javascript
复制
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子句。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2017-06-07 14:24:32

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

为什么会这样呢?

应该给它一个迭代器,它生成字符串作为内容。您不能访问它的内容,除非迭代响应对象本身。只有当响应返回给客户端时,才会发生这种情况。

视图函数返回迭代器(在您的例子中是生成器),但是当您仍然在函数中时,它不会被完全迭代。这就是为什么在get方法中从未捕获异常的原因。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44410653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档