Python rest_framework.renderers.JSONRenderer() Examples
The following are 30
code examples of rest_framework.renderers.JSONRenderer().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.renderers
, or try the search function
.
Example #1
Source File: utils.py From django-rest-messaging with ISC License | 7 votes |
def parse_json_response(json): """ parse the json response """ rendered = JSONRenderer().render(json) stream = BytesIO(rendered) return JSONParser().parse(stream)
Example #2
Source File: test_html_renderer.py From DjangoRestMultipleModels with MIT License | 6 votes |
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)
Example #3
Source File: import_export.py From ontask_b with MIT License | 6 votes |
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
Example #4
Source File: test_cache.py From course-discovery with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #5
Source File: test_views.py From credentials with GNU Affero General Public License v3.0 | 6 votes |
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))
Example #6
Source File: renderers.py From trace-examples with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 })
Example #7
Source File: renderers.py From boss with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: middleware.py From ChRIS_ultron_backEnd with MIT License | 6 votes |
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)
Example #9
Source File: operations.py From cognitive with Apache License 2.0 | 6 votes |
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)
Example #10
Source File: operations.py From cognitive with Apache License 2.0 | 6 votes |
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)
Example #11
Source File: renderers.py From aws-workshop with MIT License | 6 votes |
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 })
Example #12
Source File: workflows.py From cognitive with Apache License 2.0 | 6 votes |
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)
Example #13
Source File: renderers.py From normandy with Mozilla Public License 2.0 | 5 votes |
def get_default_renderer(self, view): return renderers.JSONRenderer()
Example #14
Source File: views.py From ansible-mezzanine with MIT License | 5 votes |
def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs)
Example #15
Source File: adapters.py From drf-schema-adapter with MIT License | 5 votes |
def render(self, data): from rest_framework.renderers import JSONRenderer renderer = JSONRenderer() return renderer.render(data)
Example #16
Source File: import_export.py From ontask_b with MIT License | 5 votes |
def export( request: http.HttpRequest, pklist: str, workflow: Optional[models.Workflow] = None, ) -> http.HttpResponse: """Export the actions given as comma separated list of ids. :param request: :param pklist: comma separated list of action ids as strs :param workflow: Set by the decorators (current workflow) :return: HTTP response """ del request try: action_ids = [int(a_idx) for a_idx in pklist.split(',')] except ValueError: return redirect('home') # Serialize the content and return data serializer = serializers.ActionSelfcontainedSerializer( instance=workflow.actions.filter(id__in=action_ids), many=True, required=True) # Get the in-memory file to compress zbuf = BytesIO() zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf) zfile.write(JSONRenderer().render(serializer.data)) zfile.close() # Attach the compressed value to the response and send compressed_content = zbuf.getvalue() response = http.HttpResponse(compressed_content) response['Content-Type'] = 'application/octet-stream' response['Content-Transfer-Encoding'] = 'binary' response['Content-Disposition'] = ( 'attachment; filename="ontask_actions_{0}.gz"'.format( datetime.datetime.now().strftime('%y%m%d_%H%M%S'))) response['Content-Length'] = str(len(compressed_content)) return response
Example #17
Source File: react_polls.py From adhocracy4 with GNU Affero General Public License v3.0 | 5 votes |
def react_polls(context, question): question_serializer = serializers.QuestionSerializer( question, context={'request': context['request']} ) return format_html( '<div data-a4-widget="polls" data-question="{question}"></div>', question=JSONRenderer() .render(question_serializer.data) .decode("utf-8") )
Example #18
Source File: react_polls.py From adhocracy4 with GNU Affero General Public License v3.0 | 5 votes |
def react_poll_form(poll, reload_on_success=False): serializer = serializers.PollSerializer(poll) data_poll = JSONRenderer().render(serializer.data).decode("utf-8") reload_on_success = json.dumps(reload_on_success) return format_html( ( '<div data-a4-widget="poll-management" data-module="{module}" ' ' data-poll="{poll}" data-reloadOnSuccess="{reload_on_success}">' '</div>' ), module=poll.module.pk, poll=data_poll, reload_on_success=reload_on_success, )
Example #19
Source File: views.py From Django-RESTful-Web-Services with MIT License | 5 votes |
def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs)
Example #20
Source File: views.py From Django-RESTful-Web-Services with MIT License | 5 votes |
def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs)
Example #21
Source File: test_views.py From credentials with GNU Affero General Public License v3.0 | 5 votes |
def test_create_with_existing_user_credential(self): """ Verify that, if a user has already been issued a credential, further attempts to issue the same credential will NOT create a new credential, but update the attributes of the existing credential. """ user_credential = UserCredentialFactory(credential__site=self.site) self.authenticate_user(self.user) self.add_user_permission(self.user, 'add_usercredential') # POSTing the exact data that exists in the database should not change the UserCredential data = self.serialize_user_credential(user_credential) response = self.client.post(self.list_path, data=JSONRenderer().render(data), content_type=JSON_CONTENT_TYPE) self.assertEqual(response.status_code, 201) # POSTing with modified status/attributes should update the existing UserCredential data = self.serialize_user_credential(user_credential) expected_attribute = UserCredentialAttributeFactory.build() data['status'] = 'revoked' data['attributes'] = [ UserCredentialAttributeSerializer(expected_attribute).data ] response = self.client.post(self.list_path, data=JSONRenderer().render(data), content_type=JSON_CONTENT_TYPE) self.assertEqual(response.status_code, 201) user_credential.refresh_from_db() self.assertEqual(response.data, self.serialize_user_credential(user_credential)) self.assertEqual(user_credential.attributes.count(), 1) actual_attribute = user_credential.attributes.first() self.assertEqual(actual_attribute.name, expected_attribute.name) self.assertEqual(actual_attribute.value, expected_attribute.value)
Example #22
Source File: views.py From edx-analytics-data-api with GNU Affero General Public License v3.0 | 5 votes |
def _handle_error(status_code): info = { 'status': status_code } renderer = JSONRenderer() content_type = '{media}; charset={charset}'.format(media=renderer.media_type, charset=renderer.charset) return HttpResponse(renderer.render(info), content_type=content_type, status=status_code)
Example #23
Source File: views.py From Learning-Path-Learn-Web-Development-with-Python with MIT License | 5 votes |
def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs)
Example #24
Source File: views.py From Learning-Path-Learn-Web-Development-with-Python with MIT License | 5 votes |
def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs)
Example #25
Source File: views.py From logtacts with MIT License | 5 votes |
def get_renderers(self): renderers = [api_renderers.JSONRenderer] if self.request.user.is_staff: renderers += [api_renderers.BrowsableAPIRenderer] return [renderer() for renderer in renderers]
Example #26
Source File: views.py From openstax-cms with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs)
Example #27
Source File: test_utils.py From micromasters with BSD 3-Clause "New" or "Revised" License | 5 votes |
def assert_drf_json_equal(obj1, obj2): """ Asserts that two objects are equal after a round trip through JSON serialization/deserialization. Particularly helpful when testing DRF serializers where you may get back OrderedDict and other such objects. Args: obj1 (object): the first object obj2 (object): the second object """ json_renderer = JSONRenderer() converted1 = json.loads(json_renderer.render(obj1)) converted2 = json.loads(json_renderer.render(obj2)) assert converted1 == converted2
Example #28
Source File: search_views.py From intake with MIT License | 5 votes |
def get_response(self, data): json = JSONRenderer().render(data) return HttpResponse(json, content_type="application/json")
Example #29
Source File: views.py From FIR with GNU General Public License v3.0 | 5 votes |
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 ===========================================================
Example #30
Source File: test_user_permissions.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
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)