Django请求数据返回str而不是list

时间:2015-07-13 20:21:09

标签: python django django-rest-framework

我正在使用Django和REST框架开发REST api。我有一个端点,它接受这种json的POST请求:

{
        "pipeline": ["Bayes"],
        "material": [
            "Rakastan iloisuutta!",
            "Autojen kanssa pitää olla varovainen.",
            "Paska kesä taas. Kylmää ja sataa"
        ]
    }

这是一个机器学习分析api,json告诉使用贝叶斯分类器提供字符串并返回结果。当我通过执行post请求手动测试它时,这工作正常。但是,当我尝试编写单元测试时,它会崩溃。我有以下测试:

class ClassifyTextAPITests(APITestCase):
    fixtures = ['fixtures/analyzerfixtures.json'] #suboptimal fixture since requires bayes.pkl in /assets/classifiers folder

    def test_classification(self):
        """ Make sure that the API will respond correctly when required url params are supplied.
        """
        response = self.client.post(reverse('analyzer_api:classifytext'), {
            "pipeline": ["Bayes"],
            "material": [
                "Rakastan iloisuutta!",
                "Autojen kanssa pitää olla varovainen.",
                "Paska kesä taas. Kylmää ja sataa",
            ]
        })
        self.assertTrue(status.is_success(response.status_code))
        self.assertEqual(response.data[0], 1)

每次测试失败,因为后者断言给出“AssertionError:'P'!= 1”

这是我的观看代码:

class ClassifyText(APIView):
    """
    Takes text snippet as a parameter and returns analyzed result.
    """
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.AllowAny,)
    parser_classes = (JSONParser,)

    def post(self, request, format=None):
        try:
            self._validate_post_data(request.data)
            print("juttu", request.data["material"])
            #create pipeline from request
            pipeline = Pipeline()
            for component_name in request.data["pipeline"]:
                pipeline.add_component(component_name)

            response = pipeline.execute_pipeline(request.data['material'])
            status_code = status.HTTP_200_OK

        except Exception as e:
            response = {"message": "Please provide a proper data.",
                        "error": str(e) }
            status_code = status.HTTP_400_BAD_REQUEST

        return Response(response, status=status_code)

    def _validate_post_data(self, data):
        if "pipeline" not in data:
            raise InvalidRequest("Pipeline field is missing. Should be array of components used in analysis. Available components at /api/classifiers")

        if len(data["pipeline"]) < 1:
            raise InvalidRequest("Pipeline array is empty.")

        if "material" not in data:
            raise InvalidRequest("Material to be analyzed is missing. Please provide an array of strings.")

        if len(data["material"]) < 1:
            raise InvalidRequest("Material to be analyzed is missing, array is empty. Please provide an array of strings.")

真正有趣的部分是当我解雇调试器来检查这里发生了什么。原来那条线

request.data['material']

在我的请求中给出列表的最后一个条目,在本例中为

  

“Paskakesätaas.Kylmääjasataa”

但是,当我检查request.data的内容时,它会显示一个querydict,其中列出了管道和材料,因为它们在请求中。当我调用request.data [“material”]时,为什么我会得到字符串而不是材料列表?有没有我忘记的东西,我必须指定某种序列化器?为什么它在正常执行期间有效但不能用于测试?

我正在使用Django 1.8和Python 3.此外,我并没有将视图与任何特定模型联系起来。

最后,当我将断点放入视图时,这是我的调试器显示的内容: request.data:

QueryDict: {'material': ['Rakastan iloisuutta!', 'Autojen kanssa pitää olla varovainen.', 'Paska kesä taas. Kylmää ja sataa'], 'pipeline': ['Bayes']}

asd = request.data [“material”]:

'Paska kesä taas. Kylmää ja sataa'

3 个答案:

答案 0 :(得分:4)

这是因为QueryDict返回__getitem__中列表的最后一个值:

  

的QueryDict。的的GetItem (键)

     

返回给定键的值。如果密钥有多个值, getitem ()将返回最后一个值。如果密钥不存在,则引发django.utils.datastructures.MultiValueDictKeyError。 (这是Python标准KeyError的子类,因此您可以坚持捕获KeyError。)

https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.QueryDict.getitem

如果您发布一个表单,其中一个键映射到列表:

d = {"a": 123, "b": [1,2,3]}
requests.post("http://127.0.0.1:6666", data=d)

这是您在请求正文中获得的内容:

a=123&b=1&b=2&b=3

由于测试方法将数据作为表单发布,因此从request.data获取的是QueryDict(与request.POST相同),因此在获取request.data时,您将获得列表中的最后一个值。

要获得预期的行为,请将数据作为JSON发布在请求正文中(如@Vladir Parrado Cruz的答案)。

答案 1 :(得分:4)

默认情况下,QueryDict会在进行getitem调用时返回列表中的单个项目(或通过方括号访问,例如request.data['material']中的

您可以使用getlist方法返回密钥的所有值:
https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.QueryDict.getlist

class ClassifyText(APIView):
    """
    Takes text snippet as a parameter and returns analyzed result.
    """
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.AllowAny,)
    parser_classes = (JSONParser,)

    def post(self, request, format=None):
        try:
            self._validate_post_data(request.data)
            print("juttu", request.data["material"])
            print("juttu", request.data.getlist("material"]))
            #create pipeline from request
            pipeline = Pipeline()
            for component_name in request.data["pipeline"]:
                pipeline.add_component(component_name)

            response = pipeline.execute_pipeline(request.data.getlist('material'))
            status_code = status.HTTP_200_OK

        except Exception as e:
            response = {"message": "Please provide a proper data.",
                        "error": str(e) }
            status_code = status.HTTP_400_BAD_REQUEST

        return Response(response, status=status_code)

    def _validate_post_data(self, data):
        if "pipeline" not in data:
            raise InvalidRequest("Pipeline field is missing. Should be array of components used in analysis. Available components at /api/classifiers")

        if len(data["pipeline"]) < 1:
            raise InvalidRequest("Pipeline array is empty.")

        if "material" not in data:
            raise InvalidRequest("Material to be analyzed is missing. Please provide an array of strings.")

        if len(data["material"]) < 1:
            raise InvalidRequest("Material to be analyzed is missing, array is empty. Please provide an array of strings.")

答案 2 :(得分:2)

尝试在测试中做类似的事情:

import json

def test_classification(self):
    """ Make sure that the API will respond correctly when required url params are supplied.
    """
    response = self.client.post(
        reverse('analyzer_api:classifytext'),
        json.dumps({
            "pipeline": ["Bayes"],
            "material": [
                "Rakastan iloisuutta!",
                "Autojen kanssa pitää olla varovainen.",
                "Paska kesä taas. Kylmää ja sataa",
            ]
        }),
        content_type='application/json'
    )
    self.assertTrue(status.is_success(response.status_code))
    self.assertEqual(response.data[0], 1)

也许如果您将数据作为json发送,它将起作用。