Python rest_framework.status.HTTP_500_INTERNAL_SERVER_ERROR Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_500_INTERNAL_SERVER_ERROR(). 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: micromasters   Author: mitodl   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def custom_exception_handler(exc, context):
    """
    Custom exception handler for rest api views
    """
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    log.exception("An exception was intercepted by custom_exception_handler")
    response = exception_handler(exc, context)

    # if it is handled, just return the response
    if response is not None:
        return response

    # Otherwise format the exception only in specific cases
    if isinstance(exc, ImproperlyConfigured):
        # send the exception to Sentry anyway
        client.capture_exception()

        formatted_exception_string = "{0}: {1}".format(type(exc).__name__, str(exc))
        return Response(
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            data=[formatted_exception_string]
        )
    return None 
Example 2
Project: koku   Author: project-koku   File: tests_view.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_list_cost_model_rate_rbac_access(self):
        """Test GET /cost-models with an rbac user."""
        user_data = self._create_user_data()
        customer = self._create_customer_data()
        request_context = self._create_request_context(customer, user_data, create_customer=True, 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": ["not-a-uuid"], "write": []}},
                "expected_response": status.HTTP_500_INTERNAL_SERVER_ERROR,
            },
        ]
        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-list")
                caches["rbac"].clear()
                response = client.get(url, **request_context["request"].META)
                self.assertEqual(response.status_code, test_case.get("expected_response")) 
Example 3
Project: safe-relay-service   Author: gnosis   File: views.py    License: MIT License 6 votes vote down vote up
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if not response:
        if isinstance(exc, (SafeServiceException, SafeCreationServiceException, TransactionServiceException,
                            FundingServiceException)):
            response = Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        else:
            response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        if str(exc):
            exception_str = '{}: {}'.format(exc.__class__.__name__, exc)
        else:
            exception_str = exc.__class__.__name__
        response.data = {'exception': exception_str}

        logger.warning('%s - Exception: %s - Data received %s',
                       context['request'].build_absolute_uri(),
                       exception_str,
                       context['request'].data)
    return response 
Example 4
Project: KubeOperator   Author: KubeOperator   File: api.py    License: Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        weixin_config = request.data
        weixin = WorkWeiXin(corp_id=weixin_config['WEIXIN_CORP_ID'], corp_secret=weixin_config['WEIXIN_CORP_SECRET'],
                            agent_id=weixin_config['WEIXIN_AGENT_ID'])
        result = weixin.get_token()
        if result.success:
            redis_cli = redis.StrictRedis(host=kubeoperator.settings.REDIS_HOST,
                                          port=kubeoperator.settings.REDIS_PORT)
            redis_cli.set('WORK_WEIXIN_TOKEN', result.data['access_token'], result.data['expires_in'])
            if weixin_config.get('WEIXIN_TEST_USER') is not None and weixin_config['WEIXIN_TEST_USER'] != '':
                res = weixin.send_markdown_msg(receivers=weixin_config['WEIXIN_TEST_USER'], content={'content': '测试消息'},
                                               token=result.data['access_token'])
                if res.success:
                    return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK)
                else:
                    return Response(data={'msg': '校验失败!' + json.dumps(res.data)},
                                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            else:
                return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK)
        else:
            return Response(data={'msg': '校验失败!' + json.dumps(result.data)},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 5
Project: django-telegram-bot   Author: jlmadurga   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post(self, request, token):
        serializer = UpdateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            try:
                bot = Bot.objects.get(token=token)
                bot.handle(Update.de_json(request.data, bot._bot))
            except Bot.DoesNotExist:
                logger.warning("Token %s not associated to a bot" % token)
                return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)
            except:
                exc_info = sys.exc_info()
                traceback.print_exception(*exc_info)
                logger.error("Error processing %s for token %s" % (request.data, token))
                return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            else:
                return Response(serializer.data, status=status.HTTP_200_OK)
        logger.error("Validation error: %s from message %s" % (serializer.errors, request.data))
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
Example 6
Project: django-drf-filepond   Author: ImperialCollegeLondon   File: uploaders.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle_upload(self, request, upload_id, file_id=None):
        # Since the upload_id is being provided here as a paramter, we check
        # it is valid. This should be done by the DB but for some DBs, e.g.
        # SQLite field length validation isn't handled. The same check is
        # done for file_id in the case of POST requests.
        if not self._upload_id_valid(upload_id):
            return Response('Invalid ID for handling upload.',
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        if request.method == 'PATCH':
            return self._handle_chunk_upload(request, upload_id)
        elif request.method == 'HEAD':
            return self._handle_chunk_restart(request, upload_id)
        elif request.method == 'POST':
            if not self._file_id_valid(file_id):
                return Response('Invalid ID for handling upload.',
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            return self._handle_new_chunk_upload(request, upload_id, file_id) 
Example 7
Project: Project-Dashboard-with-Django   Author: LukaszMalucha   File: views.py    License: MIT License 6 votes vote down vote up
def post(self, request):
        data = request.data['checkout']
        total = len(data) * 5
        queryset = CharityModel.objects.all()
        my_profile = get_object_or_404(MyProfile, owner=request.user)
        if my_profile.my_wallet < total:
            return Response({"error": "Insufficient leancoins to proceed with the transaction."},
                            status=status.HTTP_400_BAD_REQUEST)
        try:
            for element in data:
                charity = get_object_or_404(queryset, pk=int(element))
                DonationModel.objects.create(donor=request.user, charity=charity)
            my_profile.my_wallet -= total
            my_profile.save()
        except Http404:
            return Response({"error": "We couldn't proceed with transaction at this time. Try again later"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response({"message": "You have successfully paid"}, status=status.HTTP_201_CREATED) 
Example 8
Project: ecommerce   Author: edx   File: publication.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _save_and_publish(self, data, course_id=None):
        """Create or update a Course and associated products, then publish the result."""
        if course_id is not None:
            data['id'] = course_id

        serializer = self.get_serializer(data=data)
        is_valid = serializer.is_valid(raise_exception=True)
        if not is_valid:
            return None

        created, failure, message = serializer.save()
        if failure:
            return Response({'error': message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        content = serializer.data
        content['message'] = message if message else None
        return Response(content, status=status.HTTP_201_CREATED if created else status.HTTP_200_OK) 
Example 9
Project: ecommerce   Author: edx   File: refunds.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def update(self, request, *args, **kwargs):
        APPROVE = 'approve'
        DENY = 'deny'
        APPROVE_PAYMENT_ONLY = 'approve_payment_only'

        action = request.data.get('action', '').lower()

        if action not in (APPROVE, DENY, APPROVE_PAYMENT_ONLY):
            raise ParseError('The action [{}] is not valid.'.format(action))

        with transaction.atomic():
            refund = self.get_object()
            result = False

            if action in (APPROVE, APPROVE_PAYMENT_ONLY):
                revoke_fulfillment = action == APPROVE
                result = refund.approve(revoke_fulfillment=revoke_fulfillment)
            elif action == DENY:
                result = refund.deny()

        http_status = status.HTTP_200_OK if result else status.HTTP_500_INTERNAL_SERVER_ERROR
        serializer = self.get_serializer(refund)
        return Response(serializer.data, status=http_status) 
Example 10
Project: ecommerce   Author: edx   File: enterprise.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def retrieve(self, request, **kwargs):
        endpoint_request_url = urlparse(request.build_absolute_uri())._replace(query=None).geturl()
        try:
            catalog = get_enterprise_catalog(
                site=request.site,
                enterprise_catalog=kwargs.get('enterprise_catalog_uuid'),
                limit=request.GET.get('limit', DEFAULT_CATALOG_PAGE_SIZE),
                page=request.GET.get('page', '1'),
                endpoint_request_url=endpoint_request_url
            )
        except (ReqConnectionError, SlumberHttpBaseException, Timeout) as exc:
            logger.exception(
                'Unable to retrieve catalog for enterprise customer! customer: %s, Exception: %s',
                kwargs.get('enterprise_catalog_uuid'),
                exc
            )
            return Response(
                {'error': 'Unable to retrieve enterprise catalog. Exception: {}'.format(six.text_type(exc))},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

        return Response(catalog) 
Example 11
Project: ecommerce   Author: edx   File: orders.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def fulfill(self, request, number=None):  # pylint: disable=unused-argument
        """ Fulfill order """
        order = self.get_object()

        if not order.is_fulfillable:
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE)

        # Get email_opt_in from the query parameters if it exists, defaulting to false
        email_opt_in = request.query_params.get('email_opt_in', False) == 'True'

        logger.info('Attempting fulfillment of order [%s]...', order.number)
        with transaction.atomic():
            post_checkout.send(
                sender=post_checkout,
                order=order,
                request=request,
                email_opt_in=email_opt_in,
            )

        if order.is_fulfillable:
            logger.warning('Fulfillment of order [%s] failed!', order.number)
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        serializer = self.get_serializer(order)
        return Response(serializer.data) 
Example 12
Project: ecommerce   Author: edx   File: courses.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def publish(self, request, pk=None):  # pylint: disable=unused-argument
        """ Publish the course to LMS. """
        course = self.get_object()
        published = False
        msg = 'Course [{course_id}] was not published to LMS ' \
              'because the switch [publish_course_modes_to_lms] is disabled.'

        if waffle.switch_is_active('publish_course_modes_to_lms'):
            published = course.publish_to_lms()
            if published:
                msg = 'Course [{course_id}] was successfully published to LMS.'
            else:
                msg = 'An error occurred while publishing [{course_id}] to LMS.'

        return Response({'status': msg.format(course_id=course.id)},
                        status=status.HTTP_200_OK if published else status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 13
Project: micromasters   Author: mitodl   File: views_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_view_response_improperly_configured(self):
        """
        Test that the SearchResultMailView will raise ImproperlyConfigured if mailgun returns 401, which
        results in returning 500 since micromasters.utils.custom_exception_handler catches ImproperlyConfigured
        """
        with patch(
            'mail.views.get_all_query_matching_emails', autospec=True, return_value=self.email_results
        ), patch(
            'mail.views.MailgunClient'
        ) as mock_mailgun_client, patch(
            'mail.views.get_mail_vars', autospec=True, return_value=self.email_vars,
        ) as mock_get_mail_vars:
            mock_mailgun_client.send_batch.side_effect = ImproperlyConfigured
            resp = self.client.post(self.search_result_mail_url, data=self.request_data, format='json')
        assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
        mock_get_mail_vars.assert_called_once_with(self.email_results) 
Example 14
Project: micromasters   Author: mitodl   File: utils_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_generate_mailgun_response_json_with_failed_json_call(self):
        """
        Tests that generate_mailgun_response_json() returns without erroring if Response.json() call fails for
        non 401 status code
        """
        # Response.json() error
        response = Mock(
            spec=Response,
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            json=lambda: (_ for _ in []).throw(ValueError),  # To get .json() to throw ValueError
            reason="reason"
        )
        self.assertDictEqual(
            generate_mailgun_response_json(response),
            {"message": response.reason}
        ) 
Example 15
Project: micromasters   Author: mitodl   File: views_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_500_error_context_logged_out(self):
        """
        Assert context values for 500 error page when logged out
        """
        # case with specific page
        with patch('ui.templatetags.render_bundle._get_bundle') as get_bundle:
            response = self.client.get('/500/')
            assert response.context['authenticated'] is False
            assert response.context['name'] == ""
            assert response.context['is_public'] is True
            assert response.context['has_zendesk_widget'] is True
            self.assertContains(response, 'Share this page', status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
            bundles = [bundle[0][1] for bundle in get_bundle.call_args_list]
            assert set(bundles) == {
                'public',
                'sentry_client',
                'style',
                'style_public',
                'zendesk_widget',
            } 
Example 16
Project: micromasters   Author: mitodl   File: api_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_add_channel_failed_create_channel(mock_staff_client, mocker):
    """If client.channels.create fails an exception should be raised"""
    response_500 = Response()
    response_500.status_code = statuses.HTTP_500_INTERNAL_SERVER_ERROR
    mock_staff_client.channels.create.return_value.raise_for_status.side_effect = HTTPError(response=response_500)

    with pytest.raises(ChannelCreationException) as ex:
        api.add_channel(
            Search.from_dict({}),
            "title",
            "name",
            "description",
            "channel_type",
            123,
            456,
        )
    assert ex.value.args[0] == "Error creating channel name"
    mock_staff_client.channels.create.return_value.raise_for_status.assert_called_with()
    assert mock_staff_client.channels.create.call_count == 1
    assert PercolateQuery.objects.count() == 0
    assert Channel.objects.count() == 0 
Example 17
Project: resilient-python-examples   Author: ibmresilient   File: views.py    License: MIT License 6 votes vote down vote up
def get(self, request, request_id):
        """ Fetch results corresponding to given request id """
        request_id = request_id.rstrip('/')
        context = SearchContext.load(request_id)
        if context is None:
            # We return "no content" because we have none
            # 404 will cause the custom threat service caller to stop processing
            return Response({"error": "'{}' was not found".format(request_id)}, status.HTTP_204_NO_CONTENT)

        try:
            matching_threats = search_artifacts(context.type, context.value)
            response = process_threat_results(matching_threats, context)

        # Keep broad exception handler, as this is an entry point to the service interface
        except Exception as ex:  # pylint: disable=broad-except
            response = Response({'error': '{}'.format(str(ex))}, status.HTTP_500_INTERNAL_SERVER_ERROR)

        return response 
Example 18
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 19
Project: koku   Author: project-koku   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, message):
        """Initialize with status code 500."""
        self.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
        self.detail = {"detail": force_text(message)} 
Example 20
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_json_500_response(self):
        """Test that the API returns a 500 error when there is invalid cost model metric map."""
        url = reverse("metrics")
        client = APIClient()
        MOCK_COST_MODEL_METRIC_MAP = [{"Invalid": "Invalid"}]
        with patch("api.metrics.constants.COST_MODEL_METRIC_MAP", MOCK_COST_MODEL_METRIC_MAP):
            response = client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 21
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_json_500_response_source_type_map(self):
        """Test that the API returns a 500 error when there is invalid source type map."""
        url = reverse("metrics")
        client = APIClient()
        MOCK_SOURCE_TYPE_MAP = {"OCP-is-missing-from-this-dict": "Invalid"}
        with patch("api.metrics.constants.SOURCE_TYPE_MAP", MOCK_SOURCE_TYPE_MAP):
            response = client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 22
Project: koku   Author: project-koku   File: tests_rbac.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def mocked_requests_get_500_text(*args, **kwargs):
    """Mock invalid response that returns non-json."""
    json_response = "Not JSON"
    return MockResponse(json_response, status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 23
Project: koku   Author: project-koku   File: rbac.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _request_user_access(self, url, headers):  # noqa: C901
        """Send request to RBAC service and handle pagination case."""
        access = []
        try:
            response = requests.get(url, headers=headers)
        except ConnectionError as err:
            LOGGER.warning("Error requesting user access: %s", err)
            RBAC_CONNECTION_ERROR_COUNTER.inc()
            raise RbacConnectionError(err)

        if response.status_code >= status.HTTP_500_INTERNAL_SERVER_ERROR:
            msg = ">=500 Response from RBAC"
            LOGGER.warning(msg)
            RBAC_CONNECTION_ERROR_COUNTER.inc()
            raise RbacConnectionError(msg)

        if response.status_code != status.HTTP_200_OK:
            try:
                error = response.json()
                LOGGER.warning("Error requesting user access: %s", error)
            except (JSONDecodeError, ValueError) as res_error:
                LOGGER.warning("Error processing failed, %s, user access: %s", response.status_code, res_error)
            return access

        # check for pagination handling
        try:
            data = response.json()
        except ValueError as res_error:
            LOGGER.error("Error processing user access: %s", res_error)
            return access

        if not isinstance(data, dict):
            LOGGER.error("Error processing user access. Unexpected response object: %s", data)
            return access

        next_link = data.get("links", {}).get("next")
        access = data.get("data", [])
        if next_link:
            next_url = f"{self.protocol}://{self.host}:{self.port}{next_link}"
            access += self._request_user_access(next_url, headers)
        return access 
Example 24
Project: koku   Author: project-koku   File: tests_view.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_cost_metric_map_500_error(self):
        """Test that the API returns a 500 error when there is invalid cost model metric map"""
        url = reverse("cost-models-list")
        client = APIClient()
        MOCK_COST_MODEL_METRIC_MAP = [{"Invalid": "Invalid"}]
        with patch("api.metrics.constants.COST_MODEL_METRIC_MAP", MOCK_COST_MODEL_METRIC_MAP):
            response = client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 25
Project: KubeOperator   Author: KubeOperator   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        email_config = request.data
        email = Email(address=email_config['SMTP_ADDRESS'], port=email_config['SMTP_PORT'],
                      username=email_config['SMTP_USERNAME'], password=email_config['SMTP_PASSWORD'])

        result = email.login()
        if result.success:
            return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK)
        else:
            return Response(data={'msg': '校验失败!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 26
Project: KubeOperator   Author: KubeOperator   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        ding_talk_config = request.data
        ding_talk = DingTalk(webhook=ding_talk_config['DINGTALK_WEBHOOK'],secret=ding_talk_config['DINGTALK_SECRET'])
        if ding_talk_config.get('DING_TALK_TEST_USER') is not None and ding_talk_config['DING_TALK_TEST_USER'] != '':
            result = ding_talk.send_markdown_msg(receivers=ding_talk_config['DING_TALK_TEST_USER'],content={'title':'测试','text':'测试消息'})
            if result.success:
                return Response(data={'msg': '校验成功!'}, status=status.HTTP_200_OK)
            else:
                return Response(data={'msg': '校验失败!' + json.dumps(result.data)},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            return Response(data={'msg': '校验失败!参数不全!'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
Example 27
Project: KubeOperator   Author: KubeOperator   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        project_name = self.kwargs['project_name']
        namespace = self.kwargs['namespace']
        cluster = Cluster.objects.get(name=project_name)
        response = HttpResponse(content_type='application/json')
        if cluster.status == Cluster.CLUSTER_STATUS_READY or cluster.status == Cluster.CLUSTER_STATUS_INSTALLING:
            return Response(data={'msg': ': 集群未创建'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        cluster_monitor = ClusterMonitor(cluster)
        try:
            result = cluster_monitor.list_pod_status(namespace)
        except Exception as e:
            logger.error(e, exc_info=True)
            return Response(data={'msg': ': 数据读取失败!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        response.write(json.dumps(result))
        return response 
Example 28
Project: KubeOperator   Author: KubeOperator   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        project_name = kwargs['project_name']
        cluster = Cluster.objects.get(name=project_name)
        if cluster.status == Cluster.CLUSTER_STATUS_READY or cluster.status == Cluster.CLUSTER_STATUS_INSTALLING:
            return Response(data={'msg': ': 集群未创建'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        cluster_monitor = ClusterMonitor(cluster)
        result = cluster_monitor.list_storage_class()
        response = HttpResponse(content_type='application/json')
        response.write(json.dumps(result))
        return response 
Example 29
Project: KubeOperator   Author: KubeOperator   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        project_name = kwargs['project_name']
        cluster = Cluster.objects.get(name=project_name)
        if cluster.status == Cluster.CLUSTER_STATUS_READY or cluster.status == Cluster.CLUSTER_STATUS_INSTALLING:
            return Response(data={'msg': ': 集群未创建'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        cluster_monitor = ClusterMonitor(cluster)
        result = cluster_monitor.get_component_status()
        response = HttpResponse(content_type='application/json')
        response.write(json.dumps(result))
        return response 
Example 30
Project: KubeOperator   Author: KubeOperator   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        project_name = kwargs['project_name']
        cluster = Cluster.objects.get(name=project_name)
        if cluster.status == Cluster.CLUSTER_STATUS_READY or cluster.status == Cluster.CLUSTER_STATUS_INSTALLING:
            return Response(data={'msg': ': 集群未创建'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        kubeops_api.cluster_monitor.delete_unused_node(cluster)
        response = HttpResponse(content_type='application/json')
        response.write(json.dumps({'msg': '检查完毕'}))
        return response