调用发布序列化器的方法并将数据传递给它

时间:2019-05-21 20:58:53

标签: python django django-rest-framework

我想通过实例化如下所示的视图来调用如下所示的类的帖子。我需要编写一个单元测试,而不是通过URL来调用此类的post方法。

class SequencingRequestSpreadsheetView(GenericAPIView):

    parser_classes = (JSONParser,)
    serializer_class = SequencingRequestSerializer
    permission_classes = (IsBioUser, )

    suffix = '.xls'
    path = settings.SEQUENCE_REQUEST_SUBMISSION

    def post(self, request, format=None, simulation_mode = False): 

我需要知道如何创建请求对象并将其传递给此函数。 我实例化了这个视图类,我尝试将请求数据作为json传递,还尝试了字典,但没有用。

如何创建请求对象并将其传递给此方法。

resp = SequencingRequestSpreadsheetView().post(request)

1 个答案:

答案 0 :(得分:1)

您可以使用RequestFactory实现所需的功能。

factory = RequestFactory()

# Build a post request. 
request = factory.post(post_url, data, ...)

# Note here that, I don't call the class view directly
# with: 
# SequencingRequestSpreadsheetView().post(request)
# instead I get the view with as_view(), and then pass
# a post request to it.
view = SequencingRequestSpreadsheetView.as_view()

response = view(request, ...)

请参阅此处的Making requests,以更好地了解RequestFactory的工作原理。