當前位置: 首頁>>代碼示例>>Python>>正文


Python renderers.JSONRenderer方法代碼示例

本文整理匯總了Python中rest_framework.renderers.JSONRenderer方法的典型用法代碼示例。如果您正苦於以下問題:Python renderers.JSONRenderer方法的具體用法?Python renderers.JSONRenderer怎麽用?Python renderers.JSONRenderer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rest_framework.renderers的用法示例。


在下文中一共展示了renderers.JSONRenderer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_html_renderer

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def test_html_renderer(self):
        """
        Testing bug in which results dict failed to be passed into template context
        """
        client = APIClient()
        response = client.get('/template', format='html')

        # test the data is formatted properly and shows up in the template
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('data', response.data)
        self.assertContains(response, "Tragedy")
        self.assertContains(response, "<html>")
        self.assertContains(response, "decrepit")

        # test that the JSONRenderer does NOT add the dictionary wrapper to the data
        response = client.get('/template?format=json')

        # test the data is formatted properly and shows up in the template
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertNotIn('data', response.data)
        self.assertNotIn('<html>', response) 
開發者ID:MattBroach,項目名稱:DjangoRestMultipleModels,代碼行數:23,代碼來源:test_html_renderer.py

示例2: render

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def render(self, data, media_type=None, renderer_context=None):
        if data.get('results', None) is not None:
            return json.dumps({
                self.pagination_object_label: data['results'],
                self.pagination_count_label: data['count']
            })

        # If the view throws an error (such as the user can't be authenticated
        # or something similar), `data` will contain an `errors` key. We want
        # the default JSONRenderer to handle rendering errors, so we need to
        # check for this case.
        elif data.get('errors', None) is not None:
            return super(ConduitJSONRenderer, self).render(data)

        else:
            return json.dumps({
                self.object_label: data
            }) 
開發者ID:tryolabs,項目名稱:aws-workshop,代碼行數:20,代碼來源:renderers.py

示例3: _cancel_v6

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def _cancel_v6(self, request, scan_id):
        """Cancels a scan job

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :param scan_id: The ID of the Scan process
        :type scan_id: int encoded as a str
        :returns: The HTTP response to send back to the user
        :rtype: :class:`rest_framework.response.Response`
        """

        canceled_ids = Scan.objects.cancel_scan(scan_id)

        resp_dict = {'id': scan_id, 'canceled_jobs': canceled_ids}
        return JsonResponse(resp_dict, status=status.HTTP_202_ACCEPTED)
        # return Response(resp_dict, status=status.HTTP_202_ACCEPTED)
        # return Response(JSONRenderer().render(canceled_ids), status=status.HTTP_202_ACCEPTED) 
開發者ID:ngageoint,項目名稱:scale,代碼行數:19,代碼來源:views.py

示例4: render

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def render(self, data, media_type=None, renderer_context=None):

        if renderer_context['response'].status_code == 403:
            renderer_context["accepted_media_type"] = 'application/json'
            self.media_type = 'application/json'
            self.format = 'json'
            err_msg = {"status": 403, "message": "Access denied, are you logged in?",
                       "code": 2005}
            jr = JSONRenderer()
            return jr.render(err_msg, 'application/json', renderer_context)

        if not data["data"].data.flags['C_CONTIGUOUS']:
            data["data"].data = np.ascontiguousarray(data["data"].data, dtype=data["data"].data.dtype)

        # Return data, squeezing time dimension if only a single point
        if data["time_request"]:
            return blosc.compress(data["data"].data, typesize=renderer_context['view'].bit_depth)
        else:
            return blosc.compress(np.squeeze(data["data"].data, axis=(0,)),
                                  typesize=renderer_context['view'].bit_depth) 
開發者ID:jhuapl-boss,項目名稱:boss,代碼行數:22,代碼來源:renderers.py

示例5: test_should_not_cache_if_waffled

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def test_should_not_cache_if_waffled(self, waffle_active):
        """ Verify that the decorator does not cache the waffle flag is turned off """
        def key_func(**kwargs):  # pylint: disable=unused-argument
            return self.cache_response_key

        class TestView(views.APIView):
            permission_classes = [permissions.AllowAny]
            renderer_classes = [JSONRenderer]

            @compressed_cache_response(key_func=key_func)
            def get(self, request, *args, **kwargs):
                return Response('test response')

        with override_flag('compressed_cache.TestView.get', active=waffle_active):

            view_instance = TestView()
            view_instance.headers = {}  # pylint: disable=attribute-defined-outside-init
            view_instance.dispatch(request=self.request)

        # Verify nothing was cached
        if waffle_active:
            self.assertIsNot(cache.get(self.cache_response_key), None)
        else:
            self.assertIs(cache.get(self.cache_response_key), None) 
開發者ID:edx,項目名稱:course-discovery,代碼行數:26,代碼來源:test_cache.py

示例6: do_export_workflow_parse

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def do_export_workflow_parse(
    workflow: models.Workflow,
    selected_actions: Optional[List[int]] = None,
) -> BytesIO:
    """Serialize the workflow and attach its content to a BytesIO object.

    :param workflow: Workflow to serialize
    :param selected_actions: Subset of actions
    :return: BytesIO
    """
    # Get the info to send from the serializer
    serializer = WorkflowExportSerializer(
        workflow,
        context={'selected_actions': selected_actions},
    )
    to_send = JSONRenderer().render(serializer.data)

    # Get the in-memory file to compress
    zbuf = BytesIO()
    zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
    zfile.write(to_send)
    zfile.close()

    return zbuf 
開發者ID:abelardopardo,項目名稱:ontask_b,代碼行數:26,代碼來源:import_export.py

示例7: test_create_with_existing_user_grade

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def test_create_with_existing_user_grade(self):
        """ Verify that, if a user has already been issued a grade, further attempts to issue the same grade
        will NOT create a new grade, but update the fields of the existing grade.
        """
        grade = UserGradeFactory(course_run=self.course_run)
        self.authenticate_user(self.user)
        self.add_user_permission(self.user, 'add_usergrade')

        # POSTing with modified data should update the existing UserGrade
        data = self.serialize_user_grade(grade)
        data['letter_grade'] = 'B'
        response = self.client.post(self.list_path, data=JSONRenderer().render(data), content_type=JSON_CONTENT_TYPE)
        self.assertEqual(response.status_code, 201)

        grade.refresh_from_db()
        self.assertEqual(grade.letter_grade, 'B')
        self.assertDictEqual(response.data, self.serialize_user_grade(grade)) 
開發者ID:edx,項目名稱:credentials,代碼行數:19,代碼來源:test_views.py

示例8: __init__

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def __init__(self, data, **kwargs):
        kwargs['status'] = data['status']
        del data['status']
        request = data['request']
        del data['request']
        mime = request.META.get('HTTP_ACCEPT')
        if mime=='application/json':
            kwargs['content_type'] = 'application/json'
            data['error'] = data['detail']
            del data['detail']
            content = JSONRenderer().render(data)
        else:
            kwargs['content_type'] = 'application/vnd.collection+json'
            self.exception = True
            renderer_context = {}
            renderer_context['request'] = request
            renderer_context['view'] = None
            renderer_context['response'] = self
            content = CollectionJsonRenderer().render(data,
                                                      renderer_context=renderer_context)
        super(RenderedResponse, self).__init__(content, **kwargs) 
開發者ID:FNNDSC,項目名稱:ChRIS_ultron_backEnd,代碼行數:23,代碼來源:middleware.py

示例9: create

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def create(self, request):
        """
        Create a workflow for an experiment
        ---
        request_serializer: WorkflowSerializer
        """
        data = json.loads(JSONRenderer().render(request.data))
        exp_id = int(data["experiment"])
        exp = Experiment.objects.get(pk=exp_id)
        print "Experiment ", exp_id, "graph_data ", data["graph_data"]
        try:  # Temporarily for accepting changes through POST requests from UI
            workflow = exp.workflow
        except Workflow.DoesNotExist:
            print "Workflow is not yet created. Creating one"
            serializer = WorkflowSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
            return send_response(request.method, serializer)
        else:
            print "Workflow already exists. Modifying one"
            serializer = WorkflowSerializer(workflow, data=request.data)
            if serializer.is_valid():
                serializer.save()
            return send_response(request.method, serializer) 
開發者ID:CiscoSystems,項目名稱:cognitive,代碼行數:26,代碼來源:workflows.py

示例10: create

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def create(self, request, operation):
        """
        Create a component for a particular experiment
        ---
        request_serializer: ComponentSerializer
        """
        data = json.loads(JSONRenderer().render(request.data))

        op = None  # TODO: [refactor] This value is probably not needed

        exp_id = int(data["experiment"])

        # TODO: [required] this statement should be surrounded by try-catch
        exp = Experiment.objects.get(pk=exp_id)

        print "Experiment ", exp_id, " Operation ", operation
        op = self.set_operation(operation, data)

        component = Component(experiment=exp, operation_type=op)
        component.save()
        serializer = ComponentSerializer(component)
        return send_response("GET", serializer) 
開發者ID:CiscoSystems,項目名稱:cognitive,代碼行數:24,代碼來源:operations.py

示例11: update

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def update(self, request, operation, pk=None):
        """
        Update a component for a particular experiment
        ---
        request_serializer: ComponentSerializer
        """
        data = json.loads(JSONRenderer().render(request.data))

        op = None  # TODO: [refactor] This value is probably not needed

        exp_id = int(data["experiment"])
        print "Experiment ", exp_id, " Operation ", operation
        op = self.set_operation(operation, data)
        comp = Component.objects.get(pk=pk)
        comp.operation_type = op
        serializer = ComponentSerializer(comp, data=request.data)
        serializer.operation_type = op
        if serializer.is_valid():
            # serializer.operation_type = op
            serializer.save()
        # TODO: response serializer.errors when is_valid() is False
        return send_response(request.method, serializer) 
開發者ID:CiscoSystems,項目名稱:cognitive,代碼行數:24,代碼來源:operations.py

示例12: get_default_renderer

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def get_default_renderer(self, view):
        return renderers.JSONRenderer() 
開發者ID:mozilla,項目名稱:normandy,代碼行數:4,代碼來源:renderers.py

示例13: parse_json_response

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def parse_json_response(json):
    """ parse the json response """
    rendered = JSONRenderer().render(json)
    stream = BytesIO(rendered)
    return JSONParser().parse(stream) 
開發者ID:raphaelgyory,項目名稱:django-rest-messaging,代碼行數:7,代碼來源:utils.py

示例14: upload

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def upload(self, request, pk):
        files = request.data['files']
        incident = get_object_or_404(Incident, pk=pk)
        files_added = []
        for i, file in enumerate(files):
            file_obj = FileWrapper(StringIO.StringIO(file['content']))
            file_obj.name = file['filename']
            description = file['description']
            f = handle_uploaded_file(file_obj, description, incident)
            files_added.append(f)
        resp_data = FileSerializer(files_added, many=True, context={'request': request}).data
        return HttpResponse(JSONRenderer().render(resp_data), content_type='application/json')


# Token Generation =========================================================== 
開發者ID:certsocietegenerale,項目名稱:FIR,代碼行數:17,代碼來源:views.py

示例15: test_manager_can_update_xform

# 需要導入模塊: from rest_framework import renderers [as 別名]
# 或者: from rest_framework.renderers import JSONRenderer [as 別名]
def test_manager_can_update_xform(self):
        self._publish_xls_form_to_project()
        alice_data = {'username': 'alice', 'email': 'alice@localhost.com'}
        self._login_user_and_profile(extra_post_data=alice_data)
        view = XFormViewSet.as_view({
            'put': 'update'
        })
        description = 'DESCRIPTION'
        request = self.factory.get('/', **self.extra)
        xfs = XFormSerializer(instance=self.xform,
                              context={'request': request})

        data = json.loads(JSONRenderer().render(xfs.data))
        data.update({'public': True, 'description': description})

        self.assertFalse(self.xform.shared)

        request = self.factory.put('/', data=data, **self.extra)
        response = view(request, pk=self.xform.id)

        # used to be a 400, but django guardian now filters those and yet
        # still return something. So the expexted behavior is a 404
        self.assertEqual(response.status_code, 404)
        self.assertFalse(self.xform.shared)

        role.ManagerRole.add(self.user, self.xform)
        request = self.factory.put('/', data=data, **self.extra)
        response = view(request, pk=self.xform.id)

        self.xform.reload()
        self.assertTrue(self.xform.shared)
        self.assertEqual(self.xform.description, description)
        self.assertEqual(response.data['public'], True)
        self.assertEqual(response.data['description'], description) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:36,代碼來源:test_user_permissions.py


注:本文中的rest_framework.renderers.JSONRenderer方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。