Python rest_framework.status.HTTP_200_OK Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_200_OK(). 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: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def update(self, request, **kwargs):
        app = self.get_object()
        old_owner = app.owner

        if request.data.get('owner'):
            if self.request.user != app.owner and not self.request.user.is_superuser:
                raise PermissionDenied()
            new_owner = get_object_or_404(User, username=request.data['owner'])
            app.owner = new_owner
            # ensure all downstream objects that are owned by this user and are part of this app
            # is also updated
            for downstream_model in [models.AppSettings, models.Build, models.Config,
                                     models.Domain, models.Release, models.TLS]:
                downstream_model.objects.filter(owner=old_owner, app=app).update(owner=new_owner)
        app.save()
        return Response(status=status.HTTP_200_OK) 
Example 2
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def app(self, request, *args, **kwargs):
        app = get_object_or_404(models.App, id=kwargs['id'])

        perm_name = "api.use_app"
        usernames = [u.id for u in get_users_with_perms(app)
                     if u.has_perm(perm_name, app)]

        data = {}
        result = models.Key.objects \
                       .filter(owner__in=usernames) \
                       .values('owner__username', 'public', 'fingerprint') \
                       .order_by('created')
        for info in result:
            user = info['owner__username']
            if user not in data:
                data[user] = []

            data[user].append({
                'key': info['public'],
                'fingerprint': info['fingerprint']
            })

        return Response(data, status=status.HTTP_200_OK) 
Example 3
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def users(self, request, *args, **kwargs):
        app = get_object_or_404(models.App, id=kwargs['id'])
        request.user = get_object_or_404(User, username=kwargs['username'])
        # check the user is authorized for this app
        if not permissions.is_app_user(request, app):
            raise PermissionDenied()

        data = {request.user.username: []}
        keys = models.Key.objects \
                     .filter(owner__username=kwargs['username']) \
                     .values('public', 'fingerprint') \
                     .order_by('created')
        if not keys:
            raise NotFound("No Keys match the given query.")

        for info in keys:
            data[request.user.username].append({
                'key': info['public'],
                'fingerprint': info['fingerprint']
            })

        return Response(data, status=status.HTTP_200_OK) 
Example 4
Project: figures   Author: appsembler   File: test_mau_views.py    License: MIT License 6 votes vote down vote up
def test_list(self, monkeypatch, sm_test_data):
        monkeypatch.setattr(django.contrib.sites.shortcuts,
                            'get_current_site',
                            lambda req: site)
        site = sm_test_data['site']
        org = sm_test_data['organization']
        co = sm_test_data['course_overviews'][0]

        if organizations_support_sites():
            caller = UserFactory()
            UserOrganizationMappingFactory(user=caller,
                                           organization=org,
                                           is_amc_admin=True)
        else:
            caller = UserFactory(is_staff=True)

        request_path = self.request_path
        request = APIRequestFactory().get(request_path)
        request.META['HTTP_HOST'] = site.domain

        force_authenticate(request, user=caller)
        view = self.view_class.as_view({'get': 'list'})
        response = view(request)
        assert response.status_code == status.HTTP_200_OK
        # TODO: Assert data are correct 
Example 5
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def add_users(self, request, *args, **kwargs):
        """
        Add users to project members.
        """
        self.check_admin_permission()

        project = self.get_object()

        users = request.data.get('users', None)
        logger.debug("Add users {} into project {}.".format(users,
            project.name))
        for user_id in users:
            user = MyUser.objects.get(id=user_id)
            project.members.add(user)

        return Response(status=status.HTTP_200_OK) 
Example 6
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def remove_users(self, request, *args, **kwargs):
        """
        Remove users from project members.
        """
        self.check_admin_permission()

        project = self.get_object()

        users = request.data.get('users', None)
        logger.debug("Remove users {} from project {}.".format(users,
            project.name))
        for user_id in users:
            user = MyUser.objects.get(id=user_id)
            project.members.remove(user)

        return Response(status=status.HTTP_200_OK) 
Example 7
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def pod_lists(self, request, *args, **kwargs):
        """
        Return the pods list of the application with json.
        """
        application = self.get_object()

        if not application:
            raise ValidationError(detail="The application doesn't exist.")

        kubeclient = KubeClient("http://{}:{}{}".format(settings.MASTER_IP,
            settings.K8S_PORT, settings.K8S_API_PATH))
        pods = kubeclient.list_pods(namespace=application.image.project.name,
            label="app={}".format(get_application_instance_name(application)))
        logger.debug(pods)

        return Response(pods, status=status.HTTP_200_OK) 
Example 8
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def logs_pod(self, request, *args, **kwargs):
        """
        Return the tail n lines logs of pod.
        """
        user = request.user

        assert 'pid' in self.kwargs
        pid = self.kwargs['pid']
        project = Project.objects.get(id=pid)

        if not check_member_in_project(project, user):
            raise PermissionDenied(detail="User {} is not in project {}."
                .format(user.username, project.name))

        assert 'pod' in self.kwargs
        pod = self.kwargs['pod']
        tailLine = int(request.query_params['tail'])

        kubeclient = KubeClient("http://{}:{}{}".format(settings.MASTER_IP,
            settings.K8S_PORT, settings.K8S_API_PATH))
        logs = kubeclient.get_logs_of_pod(project.name, pod, tailLine)
        # print(logs)

        return Response(data=logs, status=status.HTTP_200_OK) 
Example 9
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def list_pods(self, request, *args, **kwargs):
        """
        AdminUser search pods for application id.
        """
        user = self.request.user
        if not user.is_staff:
            raise PermissionDenied()

        app_id = request.GET.get('app', 0)
        try:
            application = Application.objects.get(id=app_id)
        except Exception:
            return Response(status=status.HTTP_200_OK)

        kubeclient = KubeClient("http://{}:{}{}".format(settings.MASTER_IP,
            settings.K8S_PORT, settings.K8S_API_PATH))
        pods = kubeclient.list_pods(
            namespace=application.image.project.name,
            label="app={}".format(get_application_instance_name(application)))
        logger.debug(pods)

        return Response(pods, status=status.HTTP_200_OK) 
Example 10
Project: django-rest-registration   Author: apragacz   File: test_send_reset_password_link.py    License: MIT License 6 votes vote down vote up
def test_send_link_with_username_as_verification_id_ok(self):
        user = self.create_test_user(username='testusername')
        request = self.create_post_request({
            'login': user.username,
        })
        with self.assert_one_mail_sent() as sent_emails, self.timer() as timer:
            response = self.view_func(request)
            self.assert_valid_response(response, status.HTTP_200_OK)
        sent_email = sent_emails[0]
        verification_data = self._assert_valid_verification_email(
            sent_email, user)
        self.assertEqual(verification_data['user_id'], user.username)
        url_sig_timestamp = int(verification_data['timestamp'])
        self.assertGreaterEqual(url_sig_timestamp, timer.start_time)
        self.assertLessEqual(url_sig_timestamp, timer.end_time)
        signer = ResetPasswordSigner(verification_data)
        signer.verify() 
Example 11
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_viewsets.py    License: MIT License 6 votes vote down vote up
def test_object_viewset(self):
        """
        Tests the ObjectMutlipleModelAPIViewSet with the default settings
        """
        client = APIClient()
        response = client.get('/object/', format='api')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 2)
        self.assertEqual(response.data, {
            'Play': [
                {'title': 'Romeo And Juliet', 'genre': 'Tragedy', 'year': 1597},
                {'title': "A Midsummer Night's Dream", 'genre': 'Comedy', 'year': 1600},
                {'title': 'Julius Caesar', 'genre': 'Tragedy', 'year': 1623},
                {'title': 'As You Like It', 'genre': 'Comedy', 'year': 1623},
            ],
            'Poem': [
                {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet'},
                {'title': "As a decrepit father takes delight", 'style': 'Sonnet'}
            ]
        }) 
Example 12
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_viewsets.py    License: MIT License 6 votes vote down vote up
def test_flat_viewset(self):
        """
        Tests the ObjectMutlipleModelAPIViewSet with the default settings
        """
        client = APIClient()
        response = client.get('/flat/', format='api')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 6)
        self.assertEqual(response.data, [
            {'genre': 'Tragedy', 'title': 'Romeo And Juliet', 'year': 1597, 'type': 'Play'},
            {'genre': 'Comedy', 'title': 'A Midsummer Night\'s Dream', 'year': 1600, 'type': 'Play'},
            {'genre': 'Tragedy', 'title': 'Julius Caesar', 'year': 1623, 'type': 'Play'},
            {'genre': 'Comedy', 'title': 'As You Like It', 'year': 1623, 'type': 'Play'},
            {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet', 'type': 'Poem'},
            {'title': "As a decrepit father takes delight", 'style': 'Sonnet', 'type': 'Poem'},
        ]) 
Example 13
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_html_renderer.py    License: MIT License 6 votes vote down vote up
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 14
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_object_view.py    License: MIT License 6 votes vote down vote up
def test_dynamic_querylist(self):
        """
        using get_querylist allows the construction of dynamic queryLists
        """
        view = DynamicQueryView.as_view()

        request = factory.get('/Julius-Caesar')
        with self.assertNumQueries(2):
            response = view(request, play="Julius-Caesar")

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 2)
        self.assertEqual(response.data, {
            'Play': [
                {'title': 'Julius Caesar', 'genre': 'Tragedy', 'year': 1623},
            ],
            'Poem': [
                {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet'},
                {'title': "As a decrepit father takes delight", 'style': 'Sonnet'}
            ]
        }) 
Example 15
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_object_view.py    License: MIT License 6 votes vote down vote up
def test_cached_querylist(self):
        view = CachedQueryView.as_view()

        request = factory.get('/Julius-Caesar')
        with self.assertNumQueries(2):
            response = view(request)
        with self.assertNumQueries(0):
            response = view(request)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'Play': [
                {'title': 'Romeo And Juliet', 'genre': 'Tragedy', 'year': 1597},
                {'title': "A Midsummer Night's Dream", 'genre': 'Comedy', 'year': 1600},
                {'title': 'Julius Caesar', 'genre': 'Tragedy', 'year': 1623},
                {'title': 'As You Like It', 'genre': 'Comedy', 'year': 1623},
            ],
            'Poem': [
                {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet'},
                {'title': "As a decrepit father takes delight", 'style': 'Sonnet'}
            ]
        }) 
Example 16
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_object_view.py    License: MIT License 6 votes vote down vote up
def test_search_filter_view(self):
        """
        Tests use of built in DRF filtering with ObjectMultipleModelAPIView
        """
        view = SearchFilterView.as_view()

        request = factory.get('/', {'search': 'as'})

        with self.assertNumQueries(2):
            response = view(request).render()

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'Play': [
                {'title': 'As You Like It', 'genre': 'Comedy', 'year': 1623},
            ],
            'Poem': [
                {'title': "As a decrepit father takes delight", 'style': 'Sonnet'}
            ]
        }) 
Example 17
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_flat_view.py    License: MIT License 6 votes vote down vote up
def test_new_labels(self):
        """
        Adding the 'label' key to queryList elements should use those labels
        instead of the model names
        """
        view = CustomLabelView.as_view()

        request = factory.get('/')
        with self.assertNumQueries(2):
            response = view(request).render()

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 6)
        self.assertEqual(response.data, [
            {'genre': 'Tragedy', 'title': 'Romeo And Juliet', 'year': 1597, 'type': 'Drama'},
            {'genre': 'Comedy', 'title': 'A Midsummer Night\'s Dream', 'year': 1600, 'type': 'Drama'},
            {'genre': 'Tragedy', 'title': 'Julius Caesar', 'year': 1623, 'type': 'Drama'},
            {'genre': 'Comedy', 'title': 'As You Like It', 'year': 1623, 'type': 'Drama'},
            {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet', 'type': 'Poetry'},
            {'title': "As a decrepit father takes delight", 'style': 'Sonnet', 'type': 'Poetry'},
        ]) 
Example 18
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_flat_view.py    License: MIT License 6 votes vote down vote up
def test_filter_fn_view(self):
        """
        The filter function is useful if you want to apply filtering to one query
        but not another (unlike adding view level filtering, which will filter all the
        querysets), but that filtering can't be provided at the beginning (for example, it
        needs to access a query_param).  This is testing the filter_fn.
        """

        view = FilterFnView.as_view()

        request = factory.get('/', {'letter': 'o'})

        with self.assertNumQueries(2):
            response = view(request).render()

        # Check that the plays have been filter to remove those with the letter 'o'
        # But the poems haven't been affected
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, [
            {'genre': 'Comedy', 'title': 'A Midsummer Night\'s Dream', 'year': 1600, 'type': 'Play'},
            {'genre': 'Tragedy', 'title': 'Julius Caesar', 'year': 1623, 'type': 'Play'},
            {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet', 'type': 'Poem'},
            {'title': "As a decrepit father takes delight", 'style': 'Sonnet', 'type': 'Poem'},
        ]) 
Example 19
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_flat_view.py    License: MIT License 6 votes vote down vote up
def test_dynamic_querylist(self):
        """
        using get_querylist allows the construction of dynamic queryLists
        """
        view = DynamicQueryView.as_view()

        request = factory.get('/Julius-Caesar')
        with self.assertNumQueries(2):
            response = view(request, play="Julius-Caesar")

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(len(response.data), 3)
        self.assertEqual(response.data, [
            {'title': 'Julius Caesar', 'genre': 'Tragedy', 'year': 1623, 'type': 'Play'},
            {'title': "Shall I compare thee to a summer's day?", 'style': 'Sonnet', 'type': 'Poem'},
            {'title': "As a decrepit father takes delight", 'style': 'Sonnet', 'type': 'Poem'}
        ]) 
Example 20
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_flat_view.py    License: MIT License 6 votes vote down vote up
def test_search_filter_view(self):
        """
        Tests use of built in DRF filtering with FlatMultipleModelAPIView
        """
        view = SearchFilterView.as_view()

        request = factory.get('/', {'search': 'as'})

        with self.assertNumQueries(2):
            response = view(request).render()

        # Check first page of results
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, [
            {'title': 'As You Like It', 'genre': 'Comedy', 'year': 1623, 'type': 'Play'},
            {'title': "As a decrepit father takes delight", 'style': 'Sonnet', 'type': 'Poem'},
        ]) 
Example 21
Project: resolwe   Author: genialis   File: test_permissions.py    License: Apache License 2.0 6 votes vote down vote up
def test_public_user(self):
        """Public user cannot create/edit anything"""
        assign_perm("view_collection", self.user1, self.collection)
        assign_perm("share_collection", self.user1, self.collection)

        data = {"public": {"add": ["view"]}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_200_OK)

        data = {"public": {"add": ["edit"]}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)

        data = {"public": {"remove": ["edit"]}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) 
Example 22
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_get_all_puppies(self):
        # get API response
        response = client.get(reverse('get_post_puppies'))
        # get data from db
        puppies = Puppy.objects.all()
        serializer = PuppySerializer(puppies, many=True)
        self.assertEqual(response.data, serializer.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example 23
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_get_valid_single_puppy(self):
        response = client.get(
            reverse('get_delete_update_puppy', kwargs={'pk': self.rambo.pk}))
        puppy = Puppy.objects.get(pk=self.rambo.pk)
        serializer = PuppySerializer(puppy)
        self.assertEqual(response.data, serializer.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example 24
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def logs(self, request, **kwargs):
        app = self.get_object()
        try:
            logs = app.logs(request.query_params.get('log_lines', str(settings.LOG_LINES)))
            return HttpResponse(logs, status=status.HTTP_200_OK, content_type='text/plain')
        except NotFound:
            return HttpResponse(status=status.HTTP_204_NO_CONTENT)
        except ServiceUnavailable:
            # TODO make 503
            return HttpResponse("Error accessing logs for {}".format(app.id),
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                content_type='text/plain') 
Example 25
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def list(self, *args, **kwargs):
        pods = self.get_app().list_pods(*args, **kwargs)
        data = self.get_serializer(pods, many=True).data
        # fake out pagination for now
        pagination = {'results': data, 'count': len(data)}
        return Response(pagination, status=status.HTTP_200_OK) 
Example 26
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def restart(self, *args, **kwargs):
        pods = self.get_app().restart(**kwargs)
        data = self.get_serializer(pods, many=True).data
        # fake out pagination for now
        # pagination = {'results': data, 'count': len(data)}
        pagination = data
        return Response(pagination, status=status.HTTP_200_OK) 
Example 27
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def list(self, *args, **kwargs):
        appSettings = self.get_app().appsettings_set.latest()
        data = {"addresses": appSettings.whitelist}
        return Response(data, status=status.HTTP_200_OK) 
Example 28
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        app = get_object_or_404(models.App, id=request.data['receive_repo'])
        self.user = request.user = get_object_or_404(User, username=request.data['receive_user'])
        # check the user is authorized for this app
        if not permissions.is_app_user(request, app):
            raise PermissionDenied()
        request.data['app'] = app
        request.data['owner'] = self.user
        super(BuildHookViewSet, self).create(request, *args, **kwargs)
        # return the application databag
        response = {'release': {'version': app.release_set.filter(failed=False).latest().version}}
        return Response(response, status=status.HTTP_200_OK) 
Example 29
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        app = get_object_or_404(models.App, id=request.data['receive_repo'])
        request.user = get_object_or_404(User, username=request.data['receive_user'])
        # check the user is authorized for this app
        if not permissions.is_app_user(request, app):
            raise PermissionDenied()
        config = app.release_set.filter(failed=False).latest().config
        serializer = self.get_serializer(config)
        return Response(serializer.data, status=status.HTTP_200_OK) 
Example 30
Project: figures   Author: appsembler   File: test_course_monthly_metrics_viewset.py    License: MIT License 5 votes vote down vote up
def check_response(self, response, endpoint):
        """Helper method to reduce duplication
        """
        assert response.status_code == status.HTTP_200_OK
        assert endpoint in response.data.keys()
        history_list = response.data[endpoint]['history']

        # check that we have the current month and an element for each prior
        # month for N months back where N is `months_back`
        assert len(history_list) == self.months_back + 1
        for rec in history_list:
            assert all
            (key in rec for key in ('period', 'value'))
        return True