【问题标题】:Django RestAPI - AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returnedDjango RestAPI - AssertionError:期望返回“Response”、“HttpResponse”或“HttpStreamingResponse”
【发布时间】:2021-04-14 20:54:05
【问题描述】:

我是 Django Rest 框架的新手。我正在尝试为我的项目构建 RESTapis。但是我收到以下错误-

AssertionError:应从视图返回 ResponseHttpResponseHttpStreamingResponse,但收到 <class 'rest_framework.utils.serializer_helpers.ReturnDict'>

产生这个错误的底层代码如下-

查看详情如下-

class SymbolInformation(APIView):
    '''
    Returns the Symbol Information
    '''
    def get(self, request, symbolname='NIFTY50'):
        # Capturing Inputs in Appropriate Cases
        symbolname = symbolname.upper()
        (companyname, symbol, tablename, close, change, returns, 
         upperband, lowerband, has_fno, weekly_expiry, weekly_future, 
         lotsize, isIndex, stepvalue) = get_symbol_details(symbolname=symbolname)
        data = SymbolInformationSerializer()
        print(companyname, symbol, tablename, close, change, returns, 
              upperband, lowerband, has_fno, weekly_expiry, weekly_future, 
              lotsize, isIndex, stepvalue)
        data = {'companyname': companyname, 'symbol': symbol, 'tablename': tablename, 'close': close, 'change': change,
                'returns': returns, 'upperband': upperband, 'lowerband': lowerband, 'has_fno': has_fno, 'weekly_expiry': weekly_expiry,
                'weekly_future': weekly_future, 'lotsize': lotsize, 'isIndex': isIndex, 'stepvalue': stepvalue}
        print(data)
        output = SymbolInformationSerializer(data)
        print(output.data)
        return(output.data)

get_symbol_details函数返回的实际数据如下—— 漂亮 50 漂亮 漂亮 14504.80 194.00 1.36 15955.28 13054.32 真真假 {0:75, 1:75, 2:75} 真 50

数据字典如下—— {'companyname': 'NIFTY 50', 'symbol': 'NIFTY', 'tablename': 'NIFTY', 'close': Decimal('14504.80'), 'change': Decimal('194.00'), 'returns ': Decimal('1.36'), 'upperband': 15955.28, 'lowerband': 13054.32, 'has_fno': True, 'weekly_expiry': True, 'weekly_future': False, 'lotsize': {0: 75, 1: 75, 2: 75}, 'isIndex': True, 'stepvalue': 50}

关联的Serializer代码如下-

class SymbolInformationSerializer(serializers.Serializer):
    '''
    Returns Index Constituents
    '''
    companyname = serializers.CharField(max_length=100)
    symbol = serializers.CharField(max_length=100)
    tablename = serializers.CharField(max_length=100)
    close = serializers.DecimalField(max_digits=10, decimal_places=4)
    change = serializers.DecimalField(max_digits=10, decimal_places=4)
    returns = serializers.DecimalField(max_digits=10, decimal_places=4)
    upperband = serializers.DecimalField(max_digits=10, decimal_places=4)
    lowerband = serializers.DecimalField(max_digits=10, decimal_places=4) 
    has_fno = serializers.BooleanField()
    weekly_expiry = serializers.BooleanField()
    weekly_future = serializers.BooleanField()
    lotsize = serializers.DictField()
    isIndex = serializers.BooleanField()
    stepvalue = serializers.IntegerField()

输出后序列化如下 - {'companyname': 'NIFTY 50', 'symbol': 'NIFTY', 'tablename': 'NIFTY', 'close': '14504.8000', 'change': '194.0000', 'returns': ' 1.3600', 'upperband': '15955.2800', 'lowerband': '13054.3200', 'has_fno': True, 'weekly_expiry': True, 'weekly_future': False, 'lotsize': {'0': 75, '1 ': 75, '2': 75}, 'isIndex': True, 'stepvalue': 50}

但是,我收到如下错误 -

Internal Server Error: /analysisapis/symboldetails
Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Python37\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Python37\lib\site-packages\rest_framework\views.py", line 511, in dispatch
    self.response = self.finalize_response(request, response, *args, **kwargs)
  File "C:\Python37\lib\site-packages\rest_framework\views.py", line 426, in finalize_response
    % type(response)
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'rest_framework.utils.serializer_helpers.ReturnDict'>`

请帮助我了解我错过了什么。

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    GET 方法应始终返回 HttpResponse 对象,您可以使用 JsonResponse 对象,它是 HttpResponse 的子类,有助于创建 JSON 编码的响应。

    试试这个

    from django.http import JsonResponse
    
    class SymbolInformation(APIView):
        '''
        Returns the Symbol Information
        '''
        def get(self, request, symbolname='NIFTY50'):
            # Capturing Inputs in Appropriate Cases
            symbolname = symbolname.upper()
            (companyname, symbol, tablename, close, change, returns, 
             upperband, lowerband, has_fno, weekly_expiry, weekly_future, 
             lotsize, isIndex, stepvalue) = get_symbol_details(symbolname=symbolname)
            data = SymbolInformationSerializer()
            print(companyname, symbol, tablename, close, change, returns, 
                  upperband, lowerband, has_fno, weekly_expiry, weekly_future, 
                  lotsize, isIndex, stepvalue)
            data = {'companyname': companyname, 'symbol': symbol, 'tablename': tablename, 'close': close, 'change': change,
                    'returns': returns, 'upperband': upperband, 'lowerband': lowerband, 'has_fno': has_fno, 'weekly_expiry': weekly_expiry,
                    'weekly_future': weekly_future, 'lotsize': lotsize, 'isIndex': isIndex, 'stepvalue': stepvalue}
            print(data)
            output = SymbolInformationSerializer(data)
            print(output.data)
            return JsonResponse(output.data)
    

    【讨论】:

    • 谢谢 Sumithran,这解决了问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2020-10-04
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多