首页 > 解决方案 > Django RestAPI - AssertionError:期望返回“Response”、“HttpResponse”或“HttpStreamingResponse”

问题描述

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

AssertionError: 期望一个Response, HttpResponseorHttpStreamingResponse从视图返回,但收到一个<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函数返回的实际数据如下 - NIFTY 50 NIFTY NIFTY 14504.80 194.00 1.36 15955.28 13054.32 True True False {0: 75, 1: 75, 2: 75} True 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':真,'stepvalue':50}

相关的序列化器代码如下 -

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', '返回':'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':真,'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'>`

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

标签: pythondjangodjango-rest-framework

解决方案


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)

推荐阅读