本文整理汇总了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)
示例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
})
示例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)
示例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)
示例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)
示例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
示例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))
示例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)
示例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)
示例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)
示例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)
示例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()
示例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)
示例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 ===========================================================
示例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)