Python rest_framework.status.HTTP_201_CREATED Examples
The following are 30
code examples of rest_framework.status.HTTP_201_CREATED().
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.status
, or try the search function
.
Example #1
Source File: views.py From django-puppy-store with MIT License | 7 votes |
def get_post_puppies(request): # get all puppies if request.method == 'GET': puppies = Puppy.objects.all() serializer = PuppySerializer(puppies, many=True) return Response(serializer.data) # insert a new record for a puppy if request.method == 'POST': data = { 'name': request.data.get('name'), 'age': int(request.data.get('age')), 'breed': request.data.get('breed'), 'color': request.data.get('color') } serializer = PuppySerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #2
Source File: test_rrsets_bulk.py From desec-stack with MIT License | 6 votes |
def test_bulk_post_my_rr_sets(self): with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)): response = self.client.bulk_post_rr_sets(domain_name=self.my_empty_domain.name, payload=self.data) self.assertStatus(response, status.HTTP_201_CREATED) response = self.client.get_rr_sets(self.my_empty_domain.name) self.assertStatus(response, status.HTTP_200_OK) self.assertRRSetsCount(response.data, self.data) # Check subname requirement on bulk endpoint (and uniqueness at the same time) self.assertResponse( self.client.bulk_post_rr_sets(domain_name=self.my_empty_domain.name, payload=self.data_no_subname), status.HTTP_400_BAD_REQUEST, [ {'subname': ['This field is required.']}, {'non_field_errors': ['Another RRset with the same subdomain and type exists for this domain.']} ] )
Example #3
Source File: views.py From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 | 6 votes |
def post(self, request, format=None): """ curl -X POST -S \ -H 'Accept: application/json' \ -H 'Content-Type: multipart/form-data' \ -H 'Authorization: Token {header_token_key}' \ -F "selection={selection_code/url_code}" \ -F "name={candidate name}" \ -F "about={about}" \ -F "photo=@/path/to/your_photo.jpg;type=image/jpg" \ http://localhost:8000/api/v1/candidates """ serializer = CandidateSerializer(data=request.data) if serializer.is_valid(): serializer.save( selection=Selection.objects.get(code=request.data.get('selection')), photo=request.data.get('photo') ) return Response(data=serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #4
Source File: api.py From longclaw with MIT License | 6 votes |
def create(self, request): """Create a new product request """ variant_id = request.data.get("variant_id", None) if variant_id is not None: variant = ProductVariant.objects.get(id=variant_id) product_request = ProductRequest(variant=variant) product_request.save() serializer = self.serializer_class(product_request) response = Response(data=serializer.data, status=status.HTTP_201_CREATED) else: response = Response( {"message": "Missing 'variant_id'"}, status=status.HTTP_400_BAD_REQUEST) return response
Example #5
Source File: test_domains.py From desec-stack with MIT License | 6 votes |
def test_create_domain_under_public_suffix_with_private_parent(self): name = 'amazonaws.com' with self.assertPdnsRequests(self.requests_desec_domain_creation(name)[:-1]), PDNSChangeTracker(): Domain(owner=self.create_user(), name=name).save() self.assertTrue(Domain.objects.filter(name=name).exists()) # If amazonaws.com is owned by another user, we cannot register test.s4.amazonaws.com name = 'test.s4.amazonaws.com' response = self.client.post(self.reverse('v1:domain-list'), {'name': name}) self.assertStatus(response, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data['name'][0].code, 'name_unavailable') # s3.amazonaws.com is a public suffix. Therefore, test.s3.amazonaws.com can be # registered even if the parent zone amazonaws.com is owned by another user name = 'test.s3.amazonaws.com' psl_cm = self.get_psl_context_manager('s3.amazonaws.com') with psl_cm, self.assertPdnsRequests(self.requests_desec_domain_creation(name)): response = self.client.post(self.reverse('v1:domain-list'), {'name': name}) self.assertStatus(response, status.HTTP_201_CREATED)
Example #6
Source File: test_domains.py From desec-stack with MIT License | 6 votes |
def test_create_domains(self): self.owner.limit_domains = 100 self.owner.save() for name in [ '0.8.0.0.0.1.c.a.2.4.6.0.c.e.e.d.4.4.0.1.a.0.1.0.8.f.4.0.1.0.a.2.ip6.arpa', 'very.long.domain.name.' + self.random_domain_name(), self.random_domain_name(), ]: with self.assertPdnsRequests(self.requests_desec_domain_creation(name)): response = self.client.post(self.reverse('v1:domain-list'), {'name': name}) self.assertStatus(response, status.HTTP_201_CREATED) self.assertTrue(all(field in response.data for field in ['created', 'published', 'name', 'keys', 'minimum_ttl', 'touched'])) self.assertEqual(len(mail.outbox), 0) self.assertTrue(isinstance(response.data['keys'], list)) with self.assertPdnsRequests(self.request_pdns_zone_retrieve_crypto_keys(name)): self.assertStatus( self.client.get(self.reverse('v1:domain-detail', name=name), {'name': name}), status.HTTP_200_OK ) response = self.client.get_rr_sets(name, type='NS', subname='') self.assertStatus(response, status.HTTP_200_OK) self.assertContainsRRSets(response.data, [dict(subname='', records=settings.DEFAULT_NS, type='NS')])
Example #7
Source File: test_donations.py From desec-stack with MIT License | 6 votes |
def test_create_donation(self): url = reverse('v1:donation') data = { 'name': 'Komplizierter Vörnämü-ßßß 马大为', 'iban': 'DE89370400440532013000', 'bic': 'BYLADEM1SWU', 'amount': 123.45, 'message': 'hi there, thank you. Also, some random chars: ™ • ½ ¼ ¾ ⅓ ⅔ † ‡ µ ¢ £ € « » ♤ ♧ ♥ ♢ ¿ ', 'email': 'email@example.com', } response = self.client.post(url, data) self.assertTrue(mail.outbox) email_internal = str(mail.outbox[0].message()) direct_debit = str(mail.outbox[0].attachments[0][1]) self.assertStatus(response, status.HTTP_201_CREATED) self.assertEqual(len(mail.outbox), 2) self.assertEqual(response.data['iban'], data['iban']) self.assertTrue('Komplizierter Vornamu' in direct_debit) self.assertTrue(data['iban'] in email_internal)
Example #8
Source File: test_data.py From resolwe with Apache License 2.0 | 6 votes |
def test_post(self): # logged-in user w/ perms collection_n = Data.objects.count() resp = self._post(self.data, self.user1) self.assertEqual(resp.status_code, status.HTTP_201_CREATED) self.assertEqual(Data.objects.count(), collection_n + 1) d = Data.objects.get(pk=resp.data["id"]) self.assertTrue(now() - d.modified < timedelta(seconds=1)) self.assertTrue(now() - d.created < timedelta(seconds=1)) self.assertEqual(d.status, "OK") self.assertTrue(now() - d.started < timedelta(seconds=1)) self.assertTrue(now() - d.finished < timedelta(seconds=1)) self.assertEqual(d.contributor_id, self.user1.pk)
Example #9
Source File: test_long_refresh_token_views.py From django-rest-framework-jwt-refresh-token with MIT License | 6 votes |
def test_revoke_refresh_token(self): self.client.credentials( HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler( utils.jwt_payload_handler(self.user))) response = self.client.post(self.revoke_url) self.assertEqual( response.status_code, status.HTTP_201_CREATED, (response.status_code, response.content) ) new_rt = self.user.refresh_tokens.get() self.assertEqual( response.data, {'key': new_rt.key, 'app': new_rt.app, 'user': self.user.pk, 'created': new_rt.created.isoformat()[:-6] + 'Z', }) response = self.client.post(self.revoke_url) self.assertEqual( response.status_code, status.HTTP_404_NOT_FOUND, (response.status_code, response.content) )
Example #10
Source File: test_relations.py From resolwe with Apache License 2.0 | 6 votes |
def test_create_only_entity(self): data = { "collection": {"id": self.collection.pk}, "type": "group", "category": "clones", "partitions": [{"entity": self.entity_3.pk}, {"entity": self.entity_4.pk},], } resp = self._post(data, user=self.contributor) self.assertEqual(resp.status_code, status.HTTP_201_CREATED) self.assertEqual(Relation.objects.count(), 3) relation = Relation.objects.last() self.assertEqual(relation.collection, self.collection) self.assertEqual(relation.relationpartition_set.count(), 2) self.assertTrue( relation.relationpartition_set.filter(entity=self.entity_3.pk).exists() ) self.assertTrue( relation.relationpartition_set.filter(entity=self.entity_4.pk).exists() )
Example #11
Source File: views.py From django-rest-messaging with ISC License | 6 votes |
def post_message(self, request, pk=None): """ Pk is the pk of the Thread to which the message belongs. """ # we get the thread and check for permission thread = Thread.objects.get(id=pk) self.check_object_permissions(request, thread) # we get the body body = compat_get_request_data(self.request).get('body') # we create the message # Message.objects.save() could return an Exception try: message = Message(sender=request.rest_messaging_participant, thread=thread, body=body) message.save() serializer = SimpleMessageSerializer(message) return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception: return Response(status=status.HTTP_412_PRECONDITION_FAILED)
Example #12
Source File: views.py From django-rest-messaging with ISC License | 6 votes |
def check(self, request, *args, **kwargs): # we get the NotificationCheck instance corresponding to the user or we create it try: nc = NotificationCheck.objects.get(participant=request.rest_messaging_participant) if nc: nc.date_check = now() nc.save() status_code = status.HTTP_200_OK except Exception: nc = NotificationCheck.objects.create(participant=request.rest_messaging_participant, date_check=now()) status_code = status.HTTP_201_CREATED serializer = self.get_serializer(nc) return Response(serializer.data, status=status_code)
Example #13
Source File: views.py From aws-workshop with MIT License | 6 votes |
def post(self, request, username=None): follower = self.request.user.profile try: followee = Profile.objects.get(user__username=username) except Profile.DoesNotExist: raise NotFound('A profile with this username was not found.') if follower.pk is followee.pk: raise serializers.ValidationError('You can not follow yourself.') follower.follow(followee) serializer = self.serializer_class(followee, context={ 'request': request }) return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #14
Source File: test_api.py From django-channels-chat with MIT License | 6 votes |
def test_read_message(self): self.login_user1() url = reverse('message-api-list') message = {'recipient': 'u2', 'body': 'hello'} response = self.client.post(url, message, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.logout() # Change user self.login_user2() url = reverse('message-api-detail', kwargs={'pk': 1}) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['body'], 'hello') self.logout() # Change to another user (not in conversation) self.login_user3() response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.logout()
Example #15
Source File: memberships.py From cride-platzi with MIT License | 5 votes |
def create(self, request, *args, **kwargs): """Handle member creation from invitation code.""" serializer = AddMemberSerializer( data=request.data, context={'circle': self.circle, 'request': request} ) serializer.is_valid(raise_exception=True) member = serializer.save() data = self.get_serializer(member).data return Response(data, status=status.HTTP_201_CREATED)
Example #16
Source File: views.py From django-rest-framework-jwt-refresh-token with MIT License | 5 votes |
def revoke(self, request, key=None): obj = self.get_object() new_rt = obj.revoke() serializer = self.get_serializer(new_rt) return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #17
Source File: test_long_refresh_token_views.py From django-rest-framework-jwt-refresh-token with MIT License | 5 votes |
def test_create_refresh_token(self): data = { 'app': 'gandolf' } self.client.credentials( HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler( utils.jwt_payload_handler(self.user))) response = self.client.post(self.list_url, data, format='json') self.assertEqual( response.status_code, status.HTTP_201_CREATED, (response.status_code, response.content) ) self.assertEqual(response.data['user'], self.user.pk) self.assertEqual(response.data['app'], data['app'])
Example #18
Source File: views.py From fairtest with Apache License 2.0 | 5 votes |
def post(self, request, format=None): serializer = UserSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #19
Source File: views.py From aws-workshop with MIT License | 5 votes |
def post(self, request, article_slug=None): profile = self.request.user.profile serializer_context = {'request': request} try: article = Article.objects.get(slug=article_slug) except Article.DoesNotExist: raise NotFound('An article with this slug was not found.') profile.favorite(article) serializer = self.serializer_class(article, context=serializer_context) return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #20
Source File: tests_view.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_get_cost_model_rate_rbac_access(self): """Test GET /cost-models/{uuid} with an rbac user.""" # Remove all sources with test cost model first. self.deassociate_sources_from_test_cost_model() # create a cost model user_data = self._create_user_data() customer = self._create_customer_data() admin_request_context = self._create_request_context(customer, user_data, create_customer=True, is_admin=True) url = reverse("cost-models-list") client = APIClient() with patch("masu.processor.tasks.update_cost_model_costs.delay"): response = client.post(url, data=self.fake_data, format="json", **admin_request_context["request"].META) cost_model_uuid = response.data.get("uuid") self.assertEqual(response.status_code, status.HTTP_201_CREATED) user_data = self._create_user_data() request_context = self._create_request_context(customer, user_data, create_customer=False, is_admin=False) self.initialize_request(context={"request_context": request_context, "user_data": user_data}) test_matrix = [ {"access": {"rate": {"read": [], "write": []}}, "expected_response": status.HTTP_403_FORBIDDEN}, {"access": {"rate": {"read": ["*"], "write": []}}, "expected_response": status.HTTP_200_OK}, { "access": {"rate": {"read": [str(cost_model_uuid)], "write": []}}, "expected_response": status.HTTP_200_OK, }, ] client = APIClient() for test_case in test_matrix: with patch.object(RbacService, "get_access_for_user", return_value=test_case.get("access")): url = reverse("cost-models-detail", kwargs={"uuid": cost_model_uuid}) caches["rbac"].clear() response = client.get(url, **request_context["request"].META) self.assertEqual(response.status_code, test_case.get("expected_response"))
Example #21
Source File: views.py From aws-workshop with MIT License | 5 votes |
def create(self, request, article_slug=None): data = request.data.get('comment', {}) context = {'author': request.user.profile} try: context['article'] = Article.objects.get(slug=article_slug) except Article.DoesNotExist: raise NotFound('An article with this slug does not exist.') serializer = self.serializer_class(data=data, context=context) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #22
Source File: views.py From aws-workshop with MIT License | 5 votes |
def create(self, request): serializer_context = { 'author': request.user.profile, 'request': request } serializer_data = request.data.get('article', {}) serializer = self.serializer_class( data=serializer_data, context=serializer_context ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #23
Source File: upload_normalized_data.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def upload_normalized_data(*args, **kwargs): """Run the upload_normalized_data task.""" async_result = tasks.upload_normalized_data.delay() return Response({"AsyncResult ID": str(async_result)}, status=status.HTTP_201_CREATED)
Example #24
Source File: views_v2.py From safe-relay-service with MIT License | 5 votes |
def post(self, request, *args, **kwargs): """ Begins creation of a Gnosis Safe V1.0.0 """ serializer = self.serializer_class(data=request.data) if serializer.is_valid(): salt_nonce, owners, threshold, payment_token = (serializer.data['salt_nonce'], serializer.data['owners'], serializer.data['threshold'], serializer.data['payment_token']) safe_creation_service = SafeCreationV1_0_0ServiceProvider() safe_creation = safe_creation_service.create2_safe_tx(salt_nonce, owners, threshold, payment_token) safe_creation_response_data = SafeCreation2ResponseSerializer(data={ 'safe': safe_creation.safe.address, 'master_copy': safe_creation.master_copy, 'proxy_factory': safe_creation.proxy_factory, 'payment': safe_creation.payment, 'payment_token': safe_creation.payment_token or NULL_ADDRESS, 'payment_receiver': safe_creation.payment_receiver or NULL_ADDRESS, 'setup_data': HexBytes(safe_creation.setup_data).hex(), 'gas_estimated': safe_creation.gas_estimated, 'gas_price_estimated': safe_creation.gas_price_estimated, }) safe_creation_response_data.is_valid(raise_exception=True) return Response(status=status.HTTP_201_CREATED, data=safe_creation_response_data.data) else: return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY, data=serializer.errors)
Example #25
Source File: views_v3.py From safe-relay-service with MIT License | 5 votes |
def post(self, request, *args, **kwargs): """ Begins creation of a Gnosis Safe in its last version (v1.1.1) """ serializer = self.serializer_class(data=request.data) if serializer.is_valid(): salt_nonce, owners, threshold, payment_token = (serializer.data['salt_nonce'], serializer.data['owners'], serializer.data['threshold'], serializer.data['payment_token']) safe_creation_service = SafeCreationServiceProvider() safe_creation = safe_creation_service.create2_safe_tx(salt_nonce, owners, threshold, payment_token) safe_creation_response_data = SafeCreation2ResponseSerializer(data={ 'safe': safe_creation.safe.address, 'master_copy': safe_creation.master_copy, 'proxy_factory': safe_creation.proxy_factory, 'payment': safe_creation.payment, 'payment_token': safe_creation.payment_token or NULL_ADDRESS, 'payment_receiver': safe_creation.payment_receiver or NULL_ADDRESS, 'setup_data': HexBytes(safe_creation.setup_data).hex(), 'gas_estimated': safe_creation.gas_estimated, 'gas_price_estimated': safe_creation.gas_price_estimated, }) safe_creation_response_data.is_valid(raise_exception=True) return Response(status=status.HTTP_201_CREATED, data=safe_creation_response_data.data) else: return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY, data=serializer.errors)
Example #26
Source File: views.py From aws-workshop with MIT License | 5 votes |
def post(self, request): user = request.data.get('user', {}) # The create serializer, validate serializer, save serializer pattern # below is common and you will see it a lot throughout this course and # your own work later on. Get familiar with it. serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #27
Source File: views.py From MPContribs with MIT License | 5 votes |
def rest_submission(request): if request.method == "POST": serializer = QMCDBSetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response([serializer.errors], status=status.HTTP_400_BAD_REQUEST) return HttpResponse(status=400)
Example #28
Source File: test_api.py From django-channels-chat with MIT License | 5 votes |
def test_send_message(self): self.login_user1() url = reverse('message-api-list') message = {'recipient': 'u2', 'body': 'hello'} response = self.client.post(url, message, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.logout()
Example #29
Source File: views.py From safe-relay-service with MIT License | 5 votes |
def post(self, request, *args, **kwargs): """ Begins creation of a Safe """ serializer = self.serializer_class(data=request.data) if serializer.is_valid(): s, owners, threshold, payment_token = (serializer.data['s'], serializer.data['owners'], serializer.data['threshold'], serializer.data['payment_token']) safe_creation = SafeCreationServiceProvider().create_safe_tx(s, owners, threshold, payment_token) safe_creation_response_data = SafeCreationResponseSerializer(data={ 'signature': { 'v': safe_creation.v, 'r': safe_creation.r, 's': safe_creation.s, }, 'tx': { 'from': safe_creation.deployer, 'value': safe_creation.value, 'data': safe_creation.data.hex(), 'gas': safe_creation.gas, 'gas_price': safe_creation.gas_price, 'nonce': 0, }, 'tx_hash': safe_creation.tx_hash, 'payment': safe_creation.payment, 'payment_token': safe_creation.payment_token or NULL_ADDRESS, 'safe': safe_creation.safe.address, 'deployer': safe_creation.deployer, 'funder': safe_creation.funder, }) safe_creation_response_data.is_valid(raise_exception=True) return Response(status=status.HTTP_201_CREATED, data=safe_creation_response_data.data) else: http_status = status.HTTP_422_UNPROCESSABLE_ENTITY \ if 's' in serializer.errors else status.HTTP_400_BAD_REQUEST return Response(status=http_status, data=serializer.errors)
Example #30
Source File: test_rrsets.py From desec-stack with MIT License | 5 votes |
def test_create_my_rr_sets(self): for subname in [None, 'create-my-rr-sets', 'foo.create-my-rr-sets', 'bar.baz.foo.create-my-rr-sets']: for data in [ {'subname': subname, 'records': ['1.2.3.4'], 'ttl': 3660, 'type': 'A'}, {'subname': '' if subname is None else subname, 'records': ['desec.io.'], 'ttl': 36900, 'type': 'PTR'}, {'subname': '' if subname is None else subname, 'ttl': 3650, 'type': 'TXT', 'records': ['"foo"']}, ]: # Try POST with missing subname if data['subname'] is None: data.pop('subname') with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)): response = self.client.post_rr_set(domain_name=self.my_empty_domain.name, **data) self.assertTrue(all(field in response.data for field in ['created', 'domain', 'subname', 'name', 'records', 'ttl', 'type', 'touched'])) self.assertEqual(self.my_empty_domain.touched, max(rrset.touched for rrset in self.my_empty_domain.rrset_set.all())) self.assertStatus(response, status.HTTP_201_CREATED) # Check for uniqueness on second attempt response = self.client.post_rr_set(domain_name=self.my_empty_domain.name, **data) self.assertContains(response, 'Another RRset with the same subdomain and type exists for this domain.', status_code=status.HTTP_400_BAD_REQUEST) response = self.client.get_rr_sets(self.my_empty_domain.name) self.assertStatus(response, status.HTTP_200_OK) self.assertRRSetsCount(response.data, [data]) response = self.client.get_rr_set(self.my_empty_domain.name, data.get('subname', ''), data['type']) self.assertStatus(response, status.HTTP_200_OK) self.assertRRSet(response.data, **data)