我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用rest_framework.status.HTTP_204_NO_CONTENT。
def delete(self, request, id, format=None): """Summary Args: request (TYPE): Description id (TYPE): Description format (None, optional): Description Returns: TYPE: Description """ process = self.get_object(id) process.delete() return Response(status=status.HTTP_204_NO_CONTENT) # FBV # class MyOpenAPIRenderer(OpenAPIRenderer): # def get_customizations(self): # data = super(MyOpenAPIRenderer, self).get_customizations() # data['paths'] = custom_data['paths'] # data['info'] = custom_data['info'] # data['basePath'] = custom_data['basePath'] # return data
def delete(self, request, id, kind, format=None): """ WARNING: Force delete """ if kind == 'badge': kind = get_object_or_404(Badge, pk=id) elif kind == 'category': kind = get_object_or_404(Category, pk=id) elif kind == 'event': kind = get_object_or_404(Event, pk=id) elif kind == 'keyword': kind = get_object_or_404(Keyword, pk=id) elif kind == 'location': kind = get_object_or_404(Location, pk=id) elif kind == 'position': kind = get_object_or_404(Position, pk=id) elif kind == 'role': kind = get_object_or_404(Role, pk=id) else: return Response(status=status.HTTP_404_NOT_FOUND) kind.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def user_detail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = User.objects.get(id=id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = UserSerializer(snippet) return Response(serializer.data) elif request.method == 'PUT': serializer = UserSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': if not request.user.has_perm('OpsManage.delete_user'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def assetsLog_detail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Log_Assets.objects.get(id=id) except Log_Assets.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = AssetsLogsSerializer(snippet) return Response(serializer.data) elif request.method == 'DELETE' and request.user.has_perm('OpsManage.delete_log_assets'): if not request.user.has_perm('OpsManage.delete_log_assets'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def deploy_detail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Project_Config.objects.get(id=id) except Project_Config.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ProjectConfigSerializer(snippet) return Response(serializer.data) elif request.method == 'DELETE': if not request.user.has_perm('OpsManage.delete_project_config'): return Response(status=status.HTTP_403_FORBIDDEN) recordProject.delay(project_user=str(request.user),project_id=id,project_name=snippet.project_name,project_content="????") snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def deployLogs_detail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Log_Project_Config.objects.get(id=id) except Log_Project_Config.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = DeployLogsSerializer(snippet) return Response(serializer.data) elif request.method == 'DELETE': if not request.user.has_perm('OpsManage.delete_log_project_config'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def modelLogsdetail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Log_Ansible_Model.objects.get(id=id) except Log_Ansible_Model.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = AnsibleModelLogsSerializer(snippet) return Response(serializer.data) elif request.method == 'DELETE': if not request.user.has_perm('OpsManage.can_delete_log_ansible_model'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def playbookLogsdetail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Log_Ansible_Playbook.objects.get(id=id) except Log_Ansible_Playbook.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = AnsiblePlaybookLogsSerializer(snippet) return Response(serializer.data) elif request.method == 'DELETE': if not request.user.has_perm('OpsManage.delete_log_ansible_playbook'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def cron_detail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Cron_Config.objects.get(id=id) except Cron_Config.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CronSerializer(snippet) return Response(serializer.data) elif request.method == 'PUT': serializer = CronSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': if not request.user.has_perm('OpsManage.delete_service_assets'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def cronLogsdetail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = Log_Cron_Config.objects.get(id=id) except Log_Cron_Config.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CronLogsSerializer(snippet) return Response(serializer.data) elif request.method == 'DELETE': if not request.user.has_perm('OpsManage.delete_log_cron_config'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def test_post_should_sent_confirmation_email(self): user = create_user() user.is_active = False user.save() djoser.signals.user_activated.connect(self.signal_receiver) data = { 'uid': djoser.utils.encode_uid(user.pk), 'token': default_token_generator.make_token(user), } request = self.factory.post(data=data) response = self.view(request) self.assert_status_equal(response, status.HTTP_204_NO_CONTENT) self.assert_emails_in_mailbox(1) self.assert_email_exists(to=[user.email])
def test_delete_todo_204(self): view = ObjectListViewSet.as_view() data = { 'name':'other list', 'priority':3, 'author':self.user_author } response = self.create_todo(data) url = 'api/v1/list/%s/' % response.data['uuid'] request = self.factory.delete(url) force_authenticate(request,user=self.user_author) response = view(request,'v1',response.data['uuid']) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
def test_delete_item_204(self): view = ObjectItemViewSet.as_view() data = { 'author':self.user_author, 'note':'Note 1 for one activity', 'priority':2, 'title':'activity 1', 'uuid_list':self.list, 'assigned_to':self.user_author } response = self.create_item(data) url = 'api/v1/item/%s/' % response.data['uuid'] request = self.factory.delete(url) force_authenticate(request,user=self.user_author) response = view(request,'v1',response.data['uuid']) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
def vmServer_detail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = VmServer.objects.get(id=id) except VmServer.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = VmServerSerializer(snippet) return Response(serializer.data) elif request.method == 'PUT': serializer = VmServerSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': if not request.user.has_perm('vmanageplatform.delete_vmserver'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def vmlog_detail(request, id,format=None): """ Retrieve, update or delete a server assets instance. """ try: snippet = VmLogs.objects.get(id=id) except VmLogs.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = VmLogsSerializer(snippet) return Response(serializer.data) elif request.method == 'PUT': serializer = VmLogsSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': if not request.user.has_perm('vmanageplatform.delete_vmserver'): return Response(status=status.HTTP_403_FORBIDDEN) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def test_delete_refresth_token(self): self.client.credentials( HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler( utils.jwt_payload_handler(self.user))) response = self.client.delete(self.detail_url) self.assertEqual( response.status_code, status.HTTP_204_NO_CONTENT, (response.status_code, response.content) ) response = self.client.delete(self.detail_url1) self.assertEqual( response.status_code, status.HTTP_404_NOT_FOUND, (response.status_code, response.content) )
def test_report_update_bulk_verify_superuser(superadmin_client): user = superadmin_client.user report = ReportFactory.create(user=user) url = reverse('report-bulk') data = { 'data': { 'type': 'report-bulks', 'id': None, 'attributes': { 'verified': True } } } response = superadmin_client.post(url + '?editable=1', data) assert response.status_code == status.HTTP_204_NO_CONTENT report.refresh_from_db() assert report.verified_by == user
def test_report_update_bulk_reset_verify(superadmin_client): user = superadmin_client.user report = ReportFactory.create(verified_by=user) url = reverse('report-bulk') data = { 'data': { 'type': 'report-bulks', 'id': None, 'attributes': { 'verified': False } } } response = superadmin_client.post(url + '?editable=1', data) assert response.status_code == status.HTTP_204_NO_CONTENT report.refresh_from_db() assert report.verified_by_id is None
def testCanDeleteOwnedDomain(self): httpretty.enable() httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.') httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name+ '.') url = reverse('domain-detail', args=(self.ownedDomains[1].pk,)) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(httpretty.last_request().method, 'DELETE') self.assertEqual(httpretty.last_request().headers['Host'], 'nsmaster:8081') httpretty.reset() httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.') httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name+ '.') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertTrue(isinstance(httpretty.last_request(), httpretty.core.HTTPrettyRequestEmpty))
def testCanDeleteOwnedDynDomain(self): httpretty.enable() httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.') httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.') url = reverse('domain-detail', args=(self.ownedDomains[1].pk,)) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # FIXME In this testing scenario, the parent domain dedyn.io does not # have the proper NS and DS records set up, so we cannot test their # deletion. httpretty.reset() httpretty.register_uri(httpretty.DELETE, settings.NSLORD_PDNS_API + '/zones/' + self.ownedDomains[1].name + '.') httpretty.register_uri(httpretty.DELETE, settings.NSMASTER_PDNS_API + '/zones/' + self.ownedDomains[1].name+ '.') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertTrue(isinstance(httpretty.last_request(), httpretty.core.HTTPrettyRequestEmpty))
def testCantDeleteForeignRRset(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.otherToken) url = reverse('rrsets', args=(self.otherDomains[0].name,)) data = {'records': ['1.2.3.4'], 'ttl': 60, 'type': 'A'} response = self.client.post(url, json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) url = reverse('rrset', args=(self.otherDomains[0].name, '', 'A',)) # Try PATCH with empty records data = {'records': []} response = self.client.patch(url, json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # Try DELETE response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
def render(self, data, accepted_media_type=None, renderer_context=None): """ Render the HTML for the browsable API representation. """ self.accepted_media_type = accepted_media_type or '' self.renderer_context = renderer_context or {} template = loader.get_template(self.template) context = self.get_context(data, accepted_media_type, renderer_context) ret = template_render(template, context, request=renderer_context['request']) # Munge DELETE Response code to allow us to return content # (Do this *after* we've rendered the template so that we include # the normal deletion response code in the output) response = renderer_context['response'] if response.status_code == status.HTTP_204_NO_CONTENT: response.status_code = status.HTTP_200_OK return ret
def test_bidcycle_batch_actions(authorized_client, authorized_user): mommy.make(BidCycle, id=2, name="Bidcycle 2", cycle_start_date="2017-01-01", cycle_end_date="2018-01-01") # Try to add a saved search batch that isn't positions response = authorized_client.put(f'/api/v1/bidcycle/2/position/batch/2/') assert response.status_code == status.HTTP_400_BAD_REQUEST # Add the position batch to the bidcycle response = authorized_client.put(f'/api/v1/bidcycle/2/position/batch/1/') assert response.status_code == status.HTTP_204_NO_CONTENT # Check that we've added the positions response = authorized_client.get('/api/v1/bidcycle/2/positions/') assert response.status_code == status.HTTP_200_OK savedsearch = SavedSearch.objects.get(id=1) savedsearch.update_count() savedsearch.refresh_from_db() assert len(response.data["results"]) == savedsearch.count
def test_favorite_action_endpoints(authorized_client, authorized_user): position = mommy.make_recipe('talentmap_api.position.tests.position') response = authorized_client.get(f'/api/v1/position/{position.id}/favorite/') assert response.status_code == status.HTTP_404_NOT_FOUND response = authorized_client.put(f'/api/v1/position/{position.id}/favorite/') assert response.status_code == status.HTTP_204_NO_CONTENT response = authorized_client.get(f'/api/v1/position/{position.id}/favorite/') assert response.status_code == status.HTTP_204_NO_CONTENT response = authorized_client.delete(f'/api/v1/position/{position.id}/favorite/') assert response.status_code == status.HTTP_204_NO_CONTENT response = authorized_client.get(f'/api/v1/position/{position.id}/favorite/') assert response.status_code == status.HTTP_404_NOT_FOUND
def scale(self, request, **kwargs): new_structure = {} app = self.get_object() try: for target, count in request.data.viewitems(): new_structure[target] = int(count) models.validate_app_structure(new_structure) app.scale(request.user, new_structure) except (TypeError, ValueError) as e: return Response({'detail': 'Invalid scaling format: {}'.format(e)}, status=status.HTTP_400_BAD_REQUEST) except (EnvironmentError, ValidationError) as e: return Response({'detail': str(e)}, status=status.HTTP_400_BAD_REQUEST) except RuntimeError as e: return Response({'detail': str(e)}, status=status.HTTP_503_SERVICE_UNAVAILABLE) return Response(status=status.HTTP_204_NO_CONTENT)
def logs(self, request, **kwargs): app = self.get_object() try: return Response(app.logs(request.query_params.get('log_lines', str(settings.LOG_LINES))), status=status.HTTP_200_OK, content_type='text/plain') except requests.exceptions.RequestException: return Response("Error accessing logs for {}".format(app.id), status=status.HTTP_500_INTERNAL_SERVER_ERROR, content_type='text/plain') except EnvironmentError as e: if e.message == 'Error accessing deis-logger': return Response("Error accessing logs for {}".format(app.id), status=status.HTTP_500_INTERNAL_SERVER_ERROR, content_type='text/plain') else: return Response("No logs for {}".format(app.id), status=status.HTTP_204_NO_CONTENT, content_type='text/plain')
def snippet_detail(request, pk, format=None): """ Retrieve, update or delete a snippet instance. """ print(pk) try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = SnippetSerializer(snippet) return Response(serializer.data) elif request.method == 'PUT': serializer = SnippetSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def test_parameterval_detail_patch(self): old_rev = self.workflow.revision() request = self.factory.patch('/api/parameters/%d/' % self.floatID, {'value': '50.456' }) force_authenticate(request, user=self.user) response = parameterval_detail(request, pk=self.floatID) self.assertIs(response.status_code, status.HTTP_204_NO_CONTENT) # see that we get the new value back request = self.factory.get('/api/parameters/%d/' % self.floatID) force_authenticate(request, user=self.user) response = parameterval_detail(request, pk=self.floatID) self.assertIs(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['value'], 50.456) # changing a parameter should change the version self.workflow.refresh_from_db() self.assertNotEqual(old_rev, self.workflow.revision())
def test_wf_module_notes_post(self): request = self.factory.patch('/api/wfmodules/%d' % self.wfmodule1.id, {'notes': 'wow such doge'}) force_authenticate(request, user=self.user) response = wfmodule_detail(request, pk=self.wfmodule1.id) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # see that we get the new value back response = self.client.get('/api/wfmodules/%d/' % self.wfmodule1.id) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['notes'], 'wow such doge') # Test for error on missing notes field (and no other patachable fields) request = self.factory.patch('/api/wfmodules/%d' % self.wfmodule1.id, {'notnotes': 'forthcoming error'}) force_authenticate(request, user=self.user) response = wfmodule_detail(request, pk=self.wfmodule1.id) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # Test set/get update interval
def wfmodule_dataversion(request, pk, format=None): try: wf_module = WfModule.objects.get(pk=pk) except WfModule.DoesNotExist: return HttpResponseNotFound() if request.method == 'GET': if not wf_module.user_authorized_read(request.user): return HttpResponseNotFound() versions = wf_module.list_fetched_data_versions() current_version = wf_module.get_fetched_data_version() response = {'versions': versions, 'selected': current_version} return Response(response) elif request.method == 'PATCH': if not wf_module.user_authorized_write(request.user): return HttpResponseForbidden() ChangeDataVersionCommand.create(wf_module, datetime.datetime.strptime(request.data['selected'], "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=pytz.UTC)) return Response(status=status.HTTP_204_NO_CONTENT)
def parameterval_detail(request, pk, format=None): try: param = ParameterVal.objects.get(pk=pk) except ParameterVal.DoesNotExist: return HttpResponseNotFound() if request.method == 'GET': if not param.user_authorized_read(request.user): return HttpResponseNotFound() serializer = ParameterValSerializer(param) return Response(serializer.data) elif request.method == 'PATCH': if not param.user_authorized_write(request.user): return HttpResponseForbidden ChangeParameterCommand.create(param, request.data['value']) return Response(status=status.HTTP_204_NO_CONTENT) # Handle a parameter event (like someone clicking the fetch button) # Get or set parameter value
def parameterval_event(request, pk, format=None): try: param = ParameterVal.objects.get(pk=pk) except ParameterVal.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if not param.user_authorized_write(request.user): return HttpResponseForbidden() # change parameter value data = request.data dispatch_response = module_dispatch_event(param.wf_module, parameter=param, event=data, request=request) if dispatch_response: return dispatch_response return Response(status=status.HTTP_204_NO_CONTENT) # Return a parameter val that is actually an image
def question_detail(request, pk): question = get_object_or_404(Question, pk=pk) if request.method == 'GET': serializer = QuestionSerializer(question) return Response(serializer.data) elif request.method == 'PUT': serializer = QuestionSerializer(question, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': question.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def test_logout_old_token(self): """ Here we prove that a client can't use an expired token to logout even if logged in again with a different one :return: """ token1 = self.get_token().data['token'] self.with_token(token1).logout_current() token2 = self.get_token().data['token'] self.assertNotEqual(token1, token2) response2 = self.with_token(token1).logout_current() self.assertEqual(response2.status_code, status.HTTP_401_UNAUTHORIZED) # We can eventually go on and verify if we're still logged # and if we can finally log out using the second token response3 = self.with_token(token2).logout_current() self.assertEqual(response3.status_code, status.HTTP_204_NO_CONTENT)
def test_close_other_access(self): """ During this test a client obtains 2 tokens and we prove that authenticating with just one of them he's able to invalidate the other one using the 'logout_other' endpoint :return: """ # Warning, in the next 3 lines we're using 'magic numbers' response_list = self.get_n_tokens(2) token1 = response_list[0].data['token'] token2 = response_list[1].data['token'] response3 = self.with_token(token1).logout_other() self.assertEqual(response3.status_code, status.HTTP_200_OK) response4 = self.verify_token(token1) self.assertEqual(response4.status_code, status.HTTP_204_NO_CONTENT) response5 = self.verify_token(token2) self.assertEqual(response5.status_code, status.HTTP_401_UNAUTHORIZED)
def toggle_featured(request, entryid): """ Toggle the featured status of an entry. """ user = request.user if user.has_perm('entries.can_change_entry'): entry = None # find the entry for this id try: entry = Entry.objects.get(id=entryid) except Entry.DoesNotExist: return Response("No such entry", status=status.HTTP_404_NOT_FOUND) entry.featured = not entry.featured entry.save() return Response("Toggled featured status.", status=status.HTTP_204_NO_CONTENT) return Response( "You donot have permission to change entry featured status.", status=status.HTTP_403_FORBIDDEN)
def star(self, request, *args, **kwargs): user = request.user project = get_object_or_404(Project, pk=kwargs.get('pk')) if request.method == 'DELETE': project.user_stars.remove(user) elif request.method == 'POST': project.user_stars.add(user) elif request.method == 'GET': users = project.user_stars.values('pk') user_profiles = UserProfile.objects.filter(user__in=users) serializer = UserProfileSerializer(user_profiles, context={'request': request}, many=True) return Response(serializer.data) return Response(status=status.HTTP_204_NO_CONTENT)
def share(self, request, *args, **kwargs): self.object = self.get_object() data = {} for key, val in request.data.iteritems(): data[key] = val data.update({'xform': self.object.pk}) serializer = ShareXFormSerializer(data=data) if serializer.is_valid(): serializer.save() else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_204_NO_CONTENT)
def license_detail(request,pk,format=None): try: license = driving_license.objects.get(pk=pk) except driving_license.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = DrivingSerializer(license) return Response(serializer.data) elif request.method == 'PUT': serializer = DrivingSerializer(license,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': license.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def model_info_detail(request,pk,format=None): try: models_ = model_info.objects.get(pk=pk) except model_info.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ModelSerializer(models_) return Response(serializer.data) elif request.method == 'PUT': serializer = ModelSerializer(models_,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': models_.delete() return Response(status=status.HTTP_204_NO_CONTENT) #user_info??
def confirm(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data try: key, pk = data['key'].rsplit(':', 1) user = self.get_queryset().get(pk=pk) assert md5(user.username).hexdigest() == key except (TypeError, AssertionError, ValueError, get_user_model().DoesNotExist) as e: raise ValidationError('???????? ????') if data['new_password'] != data['new_password_confirm']: raise ValidationError('????? ?????? ?? ?????????') user.set_password(data['new_password']) user.save() return Response(status=status.HTTP_204_NO_CONTENT)
def test_successful_sign_out(self): r = self.client.sign_in(self.user.username) self.assertEqual( r.status_code, status.HTTP_200_OK, prettify_response('Sign in failed', r) ) token = r.data.get('token') r = self.client.sign_out(token) self.assertEqual( r.status_code, status.HTTP_204_NO_CONTENT, prettify_response('Sign out failed', r) ) r = self.client.authenticate(token) self.assertEqual( r.status_code, status.HTTP_403_FORBIDDEN, prettify_response('Authentication should be failed', r) )
def change_password(self, request, *args, **kwargs): serializer = ChangePasswordSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data user = self.get_object() if not user.is_active: raise ValidationError('???????????? ?????????????') if not user.check_password(serializer.validated_data['old_password']): raise ValidationError('???????? ??????') if data['new_password'] != data['new_password_confirm']: raise ValidationError('????? ?????? ?? ?????????') user.set_password(data['new_password']) user.save() return Response(status=status.HTTP_204_NO_CONTENT)
def test_delete_view(self): if self.api_is_read_only: self.assertTrue(True) else: to_delete = self.model_factory_class(**self.factory_delete_kwargs) to_delete.save() url = self.get_detail_url(to_delete) response = self.client.delete(url, format='json') if self.delete_requires_login: self.assertIn(response.status_code, [status.HTTP_403_FORBIDDEN, status.HTTP_401_UNAUTHORIZED]) self.login() response = self.client.delete(url, format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
def todo_detail(request, pk): """ Get, udpate, or delete a specific task """ try: todo = Todo.objects.get(pk=pk) except Todo.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = TodoSerializer(todo) return Response(serializer.data) elif request.method == 'PUT': serializer = TodoSerializer(todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response( serilizer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': todo.delete() return Response(status=status.HTTP_204_NO_CONTENT)