Python rest_framework.status.HTTP_404_NOT_FOUND Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_404_NOT_FOUND(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.status , or try the search function .

Example 1
Project: django-puppy-store   Author: realpython   File: views.py    License: MIT License 7 votes vote down vote up
def get_delete_update_puppy(request, pk):
    try:
        puppy = Puppy.objects.get(pk=pk)
    except Puppy.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    # get details of a single puppy
    if request.method == 'GET':
        serializer = PuppySerializer(puppy)
        return Response(serializer.data)

    # update details of a single puppy
    if request.method == 'PUT':
        serializer = PuppySerializer(puppy, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    # delete a single puppy
    if request.method == 'DELETE':
        puppy.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 2
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def stockcode_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = SC.objects.get(pk=pk)
    except SC.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ListingSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ListingSerializer(values, 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':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 3
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def ZXG_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = BlockDetail.objects.get(pk=pk)
    except BlockDetail.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = BKDetailSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = BKDetailSerializer(values, 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':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 4
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def stockcode_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = SC.objects.get(pk=pk)
    except SC.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ListingSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ListingSerializer(values, 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':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 5
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def BK_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = BlockDetail.objects.get(pk=pk)
    except BlockDetail.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = BKDetailSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = BKDetailSerializer(values, 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':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

# from .hsgtcgholdview import HSGTCG 
Example 6
Project: django-channels-chat   Author: narrowfail   File: test_api.py    License: MIT License 6 votes vote down vote up
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 7
def test_get_refresth_token_detail(self):
        self.client.credentials(
            HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler(
                utils.jwt_payload_handler(self.user)))
        response = self.client.get(self.detail_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_200_OK,
            (response.status_code, response.content)
        )
        response = self.client.get(self.detail_url1)
        self.assertEqual(
            response.status_code,
            status.HTTP_404_NOT_FOUND,
            (response.status_code, response.content)
        ) 
Example 8
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)
        ) 
Example 9
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
Project: safe-relay-service   Author: gnosis   File: test_views.py    License: MIT License 6 votes vote down vote up
def test_token_view(self):
        random_address = Account.create().address
        response = self.client.get(reverse('v1:token', args=(random_address,)))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data, {'detail': ErrorDetail(string='Not found.', code='not_found')})

        token = TokenFactory(address=random_address)
        response = self.client.get(reverse('v1:token', args=(random_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {'address': token.address,
                                         'logo_uri': token.get_full_logo_uri(),
                                         'default': token.gas,
                                         'name': token.name,
                                         'symbol': token.symbol,
                                         'description': token.description,
                                         'decimals': token.decimals,
                                         'website_uri': token.website_uri,
                                         'gas': token.gas}) 
Example 11
Project: safe-relay-service   Author: gnosis   File: views.py    License: MIT License 6 votes vote down vote up
def get(self, request, address, format=None):
        """
        Get status of the safe
        """
        if not Web3.isChecksumAddress(address):
            return Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        else:
            try:
                SafeContract.objects.get(address=address)
            except SafeContract.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)

            safe_balances = StatsServiceProvider().get_balances(address)
            serializer = self.serializer_class(data=safe_balances, many=True)
            # assert serializer.is_valid(), 'Safe Balance result not valid'
            serializer.is_valid()
            return Response(status=status.HTTP_200_OK, data=serializer.data) 
Example 12
Project: safe-relay-service   Author: gnosis   File: test_views.py    License: MIT License 6 votes vote down vote up
def test_safe_balances(self):
        safe_address = Account.create().address
        response = self.client.get(reverse('v1:safe-balances', args=(safe_address, )))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        SafeContractFactory(address=safe_address)
        value = 7
        self.send_ether(safe_address, 7)
        response = self.client.get(reverse('v1:safe-balances', args=(safe_address, )))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.json()), 1)
        self.assertIsNone(response.json()[0]['tokenAddress'])
        self.assertEqual(response.json()[0]['balance'], str(value))

        tokens_value = 12
        erc20 = self.deploy_example_erc20(tokens_value, safe_address)
        response = self.client.get(reverse('v1:safe-balances', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.json()), 1)

        EthereumEventFactory(token_address=erc20.address, to=safe_address)
        response = self.client.get(reverse('v1:safe-balances', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertCountEqual(response.json(), [{'tokenAddress': None, 'balance': str(value)},
                                                {'tokenAddress': erc20.address, 'balance': str(tokens_value)}]) 
Example 13
Project: safe-relay-service   Author: gnosis   File: test_views.py    License: MIT License 6 votes vote down vote up
def test_erc20_view(self):
        safe_address = Account().create().address
        SafeContractFactory(address=safe_address)

        response = self.client.get(reverse('v1:erc20-txs', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        ethereum_erc20_event = EthereumEventFactory(to=safe_address)
        response = self.client.get(reverse('v1:erc20-txs', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_ethereum_erc20_event = response.json()['results'][0]
        self.assertEqual(ethereum_erc20_event.token_address, response_ethereum_erc20_event['tokenAddress'])
        self.assertEqual(ethereum_erc20_event.arguments['to'], response_ethereum_erc20_event['to'])
        self.assertEqual(ethereum_erc20_event.arguments['from'], response_ethereum_erc20_event['from'])
        self.assertEqual(ethereum_erc20_event.arguments['value'], int(response_ethereum_erc20_event['value']))
        self.assertEqual(ethereum_erc20_event.ethereum_tx.to, response_ethereum_erc20_event['ethereumTx']['to'])

        EthereumEventFactory(from_=safe_address)
        EthereumEventFactory()
        response = self.client.get(reverse('v1:erc20-txs', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()['count'], 2) 
Example 14
Project: safe-relay-service   Author: gnosis   File: test_views.py    License: MIT License 6 votes vote down vote up
def test_erc721_view(self):
        safe_address = Account().create().address
        SafeContractFactory(address=safe_address)

        response = self.client.get(reverse('v1:erc721-txs', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        ethereum_erc721_event = EthereumEventFactory(to=safe_address, erc721=True)
        response = self.client.get(reverse('v1:erc721-txs', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        response_ethereum_erc721_event = response.json()['results'][0]
        self.assertEqual(ethereum_erc721_event.token_address, response_ethereum_erc721_event['tokenAddress'])
        self.assertEqual(ethereum_erc721_event.arguments['to'], response_ethereum_erc721_event['to'])
        self.assertEqual(ethereum_erc721_event.arguments['from'], response_ethereum_erc721_event['from'])
        self.assertEqual(ethereum_erc721_event.arguments['tokenId'], int(response_ethereum_erc721_event['tokenId']))
        self.assertEqual(ethereum_erc721_event.ethereum_tx.to, response_ethereum_erc721_event['ethereumTx']['to'])

        EthereumEventFactory(from_=safe_address, erc721=True)
        EthereumEventFactory(erc721=True)
        response = self.client.get(reverse('v1:erc721-txs', args=(safe_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()['count'], 2) 
Example 15
Project: kobo-predict   Author: awemulya   File: FieldsightFcmViewset.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def perform_create(self, serializer):
        try:
            device = Device.objects.get(dev_id=serializer.data["dev_id"])
        except Device.DoesNotExist:
            device = Device(dev_id=serializer.data["dev_id"])
        device.is_active = True
        device.reg_id = serializer.data["reg_id"]
        user = User.objects.filter(email__iexact=serializer.data["name"])
        if user:
            device.name = user[0].email
        else:
            user = User.objects.filter(username__iexact=serializer.data["name"])
            if user:
                device.name = user[0].email
            else:
                return response.Response(status=status.HTTP_404_NOT_FOUND)    
        device.save() 
Example 16
Project: django-celery-inspect   Author: psychok7   File: viewsets.py    License: MIT License 6 votes vote down vote up
def active_status(self, request):
        """
        This will only work if you have django-celery installed (for now).
        In case you only need to work with status codes to find out if the
        workers are up or not.
        This will only work if we assume our db only contains "active workers".
        To use this feature, you must ensure you use only named workers,
        For example: "-n worker1@localhost:8000".
        http://docs.celeryproject.org/en/latest/userguide/workers.html#starting-the-worker
        """

        app_installed = "djcelery" in settings.INSTALLED_APPS
        if not app_installed:
            return Response(status=status.HTTP_501_NOT_IMPLEMENTED)

        from djcelery.models import WorkerState

        count_workers = WorkerState.objects.all().count()
        result = self.inspect.active()

        if result is not None and count_workers == len(result):
            return Response(status=status.HTTP_200_OK)

        return Response(status=status.HTTP_404_NOT_FOUND) 
Example 17
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 6 votes vote down vote up
def test_status_delete(self):
        data = self.create_item()
        data_id = data.get("id")
        rud_url = api_reverse('api-status:detail', kwargs={"id": data_id})
        rud_data = {
            'content': "another new content"
        }
        '''
        delete method / delete
        '''
        del_response = self.client.delete(rud_url, format='json')
        self.assertEqual(del_response.status_code, status.HTTP_204_NO_CONTENT)
        '''
        Not found
        '''
        get_response = self.client.get(rud_url, format='json')
        self.assertEqual(get_response.status_code, status.HTTP_404_NOT_FOUND) 
Example 18
Project: django-rest-passwordreset   Author: anexia-it   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = serializer.validated_data['token']

        # get token validation time
        password_reset_token_validation_time = get_password_reset_token_expiry_time()

        # find token
        reset_password_token = ResetPasswordToken.objects.filter(key=token).first()

        if reset_password_token is None:
            return Response({'status': 'notfound'}, status=status.HTTP_404_NOT_FOUND)

        # check expiry date
        expiry_date = reset_password_token.created_at + timedelta(hours=password_reset_token_validation_time)

        if timezone.now() > expiry_date:
            # delete expired token
            reset_password_token.delete()
            return Response({'status': 'expired'}, status=status.HTTP_404_NOT_FOUND)
        
        return Response({'status': 'OK'}) 
Example 19
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_get_invalid_single_puppy(self):
        response = client.get(
            reverse('get_delete_update_puppy', kwargs={'pk': 30}))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) 
Example 20
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_invalid_delete_puppy(self):
        response = client.delete(
            reverse('get_delete_update_puppy', kwargs={'pk': 30}))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) 
Example 21
Project: django-rest-registration   Author: apragacz   File: api_views.py    License: MIT License 5 votes vote down vote up
def assert_response_is_not_found(response):
    assert_invalid_response(
        response,
        expected_status_code=status.HTTP_404_NOT_FOUND,
    ) 
Example 22
Project: django-rest-registration   Author: apragacz   File: base.py    License: MIT License 5 votes vote down vote up
def assert_response_is_not_found(self, response):
        self.assert_invalid_response(
            response,
            expected_status_code=status.HTTP_404_NOT_FOUND,
        ) 
Example 23
Project: django-rest-registration   Author: apragacz   File: test_verify_registration.py    License: MIT License 5 votes vote down vote up
def test_verify_disabled(self):
        user, request = self.prepare_user_and_request()
        response = self.view_func(request)

        self.assert_invalid_response(response, status.HTTP_404_NOT_FOUND)
        user.refresh_from_db()
        self.assertFalse(user.is_active) 
Example 24
Project: django-rest-registration   Author: apragacz   File: test_verify_email.py    License: MIT License 5 votes vote down vote up
def test_noverify_not_found(self):
        self.setup_user()
        signer = RegisterEmailSigner({
            'user_id': self.user.pk,
            'email': self.new_email,
        }, strict=False)
        data = signer.get_signed_data()
        request = self.create_post_request(data)
        response = self.view_func(request)
        self.assert_invalid_response(response, status.HTTP_404_NOT_FOUND)
        self.user.refresh_from_db()
        self.assertEqual(self.user.email, self.email) 
Example 25
Project: resolwe   Author: genialis   File: test_collection.py    License: Apache License 2.0 5 votes vote down vote up
def test_post(self):
        # logged-in user
        collection_n = Collection.objects.count()
        resp = self._post(self.post_data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Collection.objects.count(), collection_n + 1)

        # public user
        collection_n += 1
        resp = self._post(self.post_data)
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(Collection.objects.count(), collection_n) 
Example 26
Project: resolwe   Author: genialis   File: test_collection.py    License: Apache License 2.0 5 votes vote down vote up
def test_patch_no_perm(self):
        data = {"name": "New collection"}
        resp = self._patch(2, data, self.user2)
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
        p = Collection.objects.get(pk=2)
        self.assertEqual(p.name, "Test collection 2") 
Example 27
Project: resolwe   Author: genialis   File: test_collection.py    License: Apache License 2.0 5 votes vote down vote up
def test_delete_no_perm(self):
        resp = self._delete(2, self.user2)
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
        collection_exists = Collection.objects.filter(pk=2).exists()
        self.assertTrue(collection_exists) 
Example 28
Project: resolwe   Author: genialis   File: test_data.py    License: Apache License 2.0 5 votes vote down vote up
def test_get_detail_no_perms(self):
        # public user w/o permissions
        resp = self._get_detail(2)
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(resp.data["detail"], MESSAGES["NOT_FOUND"])

        # user w/o permissions
        resp = self._get_detail(2, self.user2)
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(resp.data["detail"], MESSAGES["NOT_FOUND"]) 
Example 29
Project: resolwe   Author: genialis   File: test_data.py    License: Apache License 2.0 5 votes vote down vote up
def test_patch_no_perms(self):
        data = {"name": "New data"}
        resp = self._patch(2, data, self.user2)
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
        d = Data.objects.get(pk=2)
        self.assertEqual(d.name, "Test data 2") 
Example 30
Project: resolwe   Author: genialis   File: test_data.py    License: Apache License 2.0 5 votes vote down vote up
def test_delete_no_perms(self):
        resp = self._delete(2, self.user2)
        self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
        query = Data.objects.filter(pk=2).exists()
        self.assertTrue(query)