Python rest_framework.status.HTTP_503_SERVICE_UNAVAILABLE Examples

The following are 24 code examples of rest_framework.status.HTTP_503_SERVICE_UNAVAILABLE(). 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 server with MIT License 6 votes vote down vote up
def get_currency_exchange_rate(request, source_currency_code, target_currency_code):
    """
    Return currency conversion rate using source and target currency codes
    :param request:
    :param source_currency_code:
    :param target_currency_code:
    :return: 503 if Free Currency Converter api fails
    :return: 200 successful
    """
    query = "{0}_{1}".format(source_currency_code, target_currency_code)
    try:
        api_response = requests.get(CURRENCY_CONVERTER_API_URL.format(query))
        api_response_json = api_response.json()
        if not api_response.ok:
            return DOWNSTREAM_ERROR_RESPONSE

        response = CurrencyItem(source=source_currency_code,
                                target=target_currency_code,
                                result=api_response_json[query])

    except Exception:
        exception_message = "Incorrect currency codes {}".format(query)
        return Response(exception_message, status=status.HTTP_503_SERVICE_UNAVAILABLE)

    return Response(response.to_json()) 
Example #2
Source File: views.py    From server with MIT License 6 votes vote down vote up
def get_help(request):
    """
    Returns HELP content from static JSON file '/api/resources/help.json'
    :param request:
    :return: 200 successful
    """
    try:
        filename = 'api/resources/help.json'
        file = open(filename, 'r')
        data = file.read()
        data = json.loads(data)
        file.close()
    except (IOError, ValueError):
        data = {"help": ["Error in fetching content."]}
        return Response(data, status=status.HTTP_503_SERVICE_UNAVAILABLE)
    except Exception as e:
        return Response(str(e), status=status.HTTP_503_SERVICE_UNAVAILABLE)
    return Response(data, status=status.HTTP_200_OK) 
Example #3
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_bulk_update_catches_exception(self):
        def view(viewset, _request, **kwargs):
            if viewset.counter == 2:
                raise Exception('BOOM')
            viewset.counter += 1
            return Response(status=status.HTTP_200_OK)

        self.viewset.counter = 0
        self.viewset.update = MethodType(view, self.viewset, mock.Mock)
        self.request.data = {'foo': {'key': 'val1'}, 'bar': {'key': 'val2'}, 'baz': {'key': 'val3'}}
        with mock.patch('logging.getLogger') as getLogger:
            response = bulk.bulk_update_impl(self.viewset, self.request)
            self.assertTrue(getLogger.return_value.error.called)
        self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #4
Source File: test_domains.py    From desec-stack with MIT License 5 votes vote down vote up
def test_create_domain_under_unsupported_public_suffix_rule(self):
        # Show lenience if the PSL library produces an UnsupportedRule exception
        name = 'unsupported.wildcard.test'
        psl_cm = self.get_psl_context_manager(UnsupportedRule)
        with psl_cm, self.assertPdnsRequests():
            response = self.client.post(self.reverse('v1:domain-list'), {'name': name})
            self.assertStatus(response, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #5
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_bulk_destroy_catches_exception(self):
        def view(viewset, _request, **kwargs):
            if viewset.counter == 2:
                raise Exception('BOOM')
            viewset.counter += 1
            return Response(status=status.HTTP_204_NO_CONTENT)

        self.viewset.counter = 0
        self.viewset.destroy = MethodType(view, self.viewset, mock.Mock)
        self.request.data = ['foo', 'bar', 'baz', 'quux']
        with mock.patch('logging.getLogger') as getLogger:
            response = bulk.bulk_destroy_impl(self.viewset, self.request)
            self.assertTrue(getLogger.return_value.error.called)
        self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #6
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_create_wrapper_catches_exceptions(self):
        def view(viewset, _request, **kwargs):
            if viewset.counter == 2:
                raise Exception('BOOM')
            viewset.counter += 1
            return Response(status=status.HTTP_201_CREATED)

        self.viewset.counter = 0
        self.viewset.create = view
        wrapped = bulk.bulk_create_wrapper(self.viewset.create)
        self.request.data = ['foo', 'bar', 'baz', 'quux']
        with mock.patch('logging.getLogger') as getLogger:
            response = wrapped(self.viewset, self.request)
            self.assertTrue(getLogger.return_value.error.called)
        self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #7
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_database_outage(self):
        """Test that the endpoint reports when the database is unavailable."""
        self._assert_health(
            status.HTTP_503_SERVICE_UNAVAILABLE,
            Status.UNAVAILABLE,
            Status.UNAVAILABLE,
        ) 
Example #8
Source File: test_views.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_status_old(self, mock_get_queue_size):
        """Test getting scheduler status with old data"""
        
        mock_get_queue_size.return_value = 0

        when = now() - datetime.timedelta(hours=1)
        status_thread = SchedulerStatusThread()
        status_thread._generate_status_json(when)

        url = '/%s/status/' % self.api
        response = self.client.generic('GET', url)
        self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE, response.content)
        result = json.loads(response.content)
        self.assertDictEqual({'detail': 'Status is over 12 seconds old'}, result) 
Example #9
Source File: test_views.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_status_empty_dict(self):
        """Test getting scheduler status with empty initialization"""

        url = '/%s/status/' % self.api
        response = self.client.generic('GET', url)
        self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE, response.content)
        result = json.loads(response.content)
        self.assertDictEqual({'detail': 'Status is missing. Scheduler may be down.'}, result) 
Example #10
Source File: user.py    From mangaki with GNU Affero General Public License v3.0 5 votes vote down vote up
def export_user_data(request: Request):
    """
    Export all user data in a zip blob and serve it through sendfile.
    """
    user = request.user

    # Cleanup old archives.
    cache_expiration = datetime.fromtimestamp(datetime.now().timestamp() - USER_EXPORT_DATA_CACHE_PERIOD)
    for archive in UserArchive.objects.filter(owner=user,
                                              updated_on__lte=cache_expiration).iterator():
        try:
            archive.local_archive.delete()
        except ValueError:
            pass
        finally:
            archive.delete()

    try:
        archive = UserArchive.objects.get(owner=user)
        return sendfile(request, archive.local_archive.path)
    except (UserArchive.DoesNotExist, OSError, IOError, ValueError):
        try:
            builder = UserDataArchiveBuilder(user)
            export(builder)
            archive, _ = UserArchive.objects.get_or_create(owner=user)
            builder.archive.close()  # save the ZIP file.
            archive.local_archive.save('data.zip',
                                       File(open(builder.archive_filename, 'rb')))
            builder.cleanup()
            return sendfile(request, archive.local_archive.path)
        except (OSError, IOError, django.db.Error) as e:
            print(e)
            return Response({}, status=status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #11
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_multiple_days_weather(request, num_of_days, city_name):
    """
    Returns 'num_of_days' forecast for given city using 'city_name'
    :param request:
    :param num_of_days:
    :param city_name:
    :return: 400 if number of days ar not in [1,16] range
    :return: 503 if OpenWeatherMap api fails
    :return: 200 successful
    """
    response = []
    if num_of_days >= 16 or num_of_days < 1:
        error_message = "Invalid number of days. Should be in between [1, 16]"
        return Response(error_message, status=status.HTTP_400_BAD_REQUEST)

    try:
        api_response = requests.get(OPEN_FORECAST_API_URL.format(city_name, num_of_days))
        api_response_json = api_response.json()
        if not api_response.ok:
            error_message = api_response_json['message']
            return Response(error_message, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        for result in api_response_json['list']:
            response.append(WeatherResponse(max_temp=to_celsius(result['temp']['max']),
                                            min_temp=to_celsius(result['temp']['min']),
                                            code=result['weather'][0]['id'],
                                            condensed=result['weather'][0]['main'],
                                            description=result['weather'][0]['description'],
                                            icon=icon_to_url(result['weather'][0]['icon']),
                                            humidity=result['humidity'],
                                            pressure=result['pressure']).to_json())
    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response) 
Example #12
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_city_weather(request, city_id):
    """
    Return current city weather using city name
    :param request:
    :param city_id:
    :return: 404 if Invalid City ID is passed
    :return: 503 if OpenWeatherMap api fails
    :return: 200 successful
    """
    try:
        city = City.objects.get(pk=city_id)
    except City.DoesNotExist:
        error_message = "Invalid City ID"
        return Response(error_message, status=status.HTTP_404_NOT_FOUND)

    try:
        api_response = requests.get(OPEN_WEATHER_API_URL.format(city.latitude, city.longitude))
        api_response_json = api_response.json()
        if not api_response.ok:
            error_message = api_response_json['message']
            return Response(error_message, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        response = WeatherResponse(temp=to_celsius(api_response_json['main']['temp']),
                                   max_temp=to_celsius(api_response_json['main']['temp_max']),
                                   min_temp=to_celsius(api_response_json['main']['temp_min']),
                                   code=api_response_json['weather'][0]['id'],
                                   condensed=api_response_json['weather'][0]['main'],
                                   description=api_response_json['weather'][0]['description'],
                                   icon=icon_to_url(api_response_json['weather'][0]['icon']),
                                   humidity=api_response_json['main']['humidity'],
                                   pressure=api_response_json['main']['pressure'])
    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response.to_json()) 
Example #13
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_restaurant(request, restaurant_id):
    """
    Returns restaurant details for a given restaurant id
    :param request:
    :param restaurant_id:
    :return: 503 if Zomato API fails
    :return: 200 successful
    """
    try:
        url = GET_RESTAURANT_API_URL.format(restaurant_id)
        api_response = requests.get(url, headers=FOOD_API_REQUEST_HEADERS)
        api_response_json = api_response.json()
        if not api_response.ok:
            error_message = api_response_json['message']
            return Response(error_message, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        response = FoodDetailedResponse(
            id=api_response_json['id'],
            name=api_response_json['name'],
            url=api_response_json['url'],
            address=api_response_json['location']['address'],
            longitude=api_response_json['location']['longitude'],
            latitude=api_response_json['location']['latitude'],
            avg2=api_response_json['average_cost_for_two'],
            price_range=api_response_json['price_range'],
            currency=api_response_json['currency'],
            img=api_response_json['featured_image'],
            agg_rating=api_response_json['user_rating']['aggregate_rating'],
            votes=api_response_json['user_rating']['votes'],
            deliver=api_response_json['has_online_delivery'],
            booking=api_response_json['has_table_booking'],
            cuisines=api_response_json['cuisines']
        ).to_json()
    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response) 
Example #14
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_all_restaurants(request, latitude, longitude):
    """
    Returns restaurant details forecast for given city using coordinates
    :param request:
    :param latitude:
    :param longitude:
    :return: 503 if Zomato API fails
    :return: 200 successful
    """
    response = []
    try:
        url = GET_ALL_RESTAURANTS_API_URL.format(latitude, longitude)
        api_response = requests.get(url, headers=FOOD_API_REQUEST_HEADERS)
        api_response_json = api_response.json()
        if not api_response.ok:
            error_message = api_response_json['message']
            return Response(error_message, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        for restaurant in api_response_json['nearby_restaurants']:
            restaurant_obj = restaurant['restaurant']
            response_obj = FoodResponse(id=restaurant_obj['id'],
                                        name=restaurant_obj['name'],
                                        url=restaurant_obj['url'],
                                        latitude=restaurant_obj['location']['latitude'],
                                        longitude=restaurant_obj['location']['longitude'],
                                        avg2=restaurant_obj['average_cost_for_two'],
                                        currency=restaurant_obj['currency'],
                                        image=restaurant_obj['featured_image'],
                                        rating=restaurant_obj['user_rating']['aggregate_rating'],
                                        votes=restaurant_obj['user_rating']['votes'],
                                        address=restaurant_obj['location']['address'])
            response.append(response_obj.to_json())
    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response) 
Example #15
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_shopping_info(request, query):
    """
    Returns a list of responses from
    :param request:
    :param query:
    :return: 503 Ebay request fails
    :return: 200 successful
    """
    try:
        api_response = requests.get(EBAY_API_URL.format(query))
        api_response_json = api_response.json()
        if not api_response.ok:
            error_message = api_response_json['errorMessage'][0]['error'][0]['message'][0]
            return Response(error_message, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        #  if ebay api returns empty response with no items
        if api_response_json['findItemsAdvancedResponse'][0]['searchResult'][0]['@count'] == '0':
            return Response([], status=status.HTTP_400_BAD_REQUEST)

        response = []
        for item in api_response_json['findItemsAdvancedResponse'][0]['searchResult'][0]['item']:
            response.append(ShoppingItem(
                name=item['title'][0],
                url=item['viewItemURL'][0],
                image=item['galleryURL'][0],
                value=item['sellingStatus'][0]['currentPrice'][0]['__value__'],
                currency=item['sellingStatus'][0]['currentPrice'][0]['@currencyId'],
            ).to_json())

    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response) 
Example #16
Source File: views.py    From server with MIT License 5 votes vote down vote up
def get_city_trends(request, city_id):
    """
    Returns a list of top trending tweets in the given city
    :param request:
    :param city_id:
    :return: 404 if invalid city id is sent
    :return: 503 if Twitter API request fails
    :return: 200 successful
    """
    try:
        city = City.objects.get(pk=city_id)
    except City.DoesNotExist:
        error_message = "Invalid City ID"
        return Response(error_message, status=status.HTTP_404_NOT_FOUND)

    twitter_auth = OAuth1(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_OAUTH_TOKEN,
                          TWITTER_OAUTH_TOKEN_SECRET)

    # check if city WOEID is in database or not
    if not city.woeid:
        try:
            url = TWITTER_TRENDS_URL + "closest.json?lat={0}&long={1}".format(city.latitude, city.longitude)
            woeid_response = requests.get(url, auth=twitter_auth)
            city.woeid = woeid_response.json()[0]['woeid']
            city.save()
        except Exception as e:
            return Response(str(e), status=status.HTTP_503_SERVICE_UNAVAILABLE)

    try:
        url = TWITTER_TRENDS_URL + "place.json?id={0}".format(city.woeid)
        api_response = requests.get(url, auth=twitter_auth)
        response = api_response.json()[0]['trends']
    except Exception:
        return DOWNSTREAM_ERROR_RESPONSE

    return Response(response) 
Example #17
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_poll_peering_sessions(self):
        url = reverse(
            "peering-api:internetexchange-poll-peering-sessions",
            kwargs={"pk": self.internet_exchange.pk},
        )
        response = self.client.post(url, **self.header)
        self.assertStatus(response, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #18
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_configure_router(self):
        url = reverse(
            "peering-api:internetexchange-configure-router",
            kwargs={"pk": self.internet_exchange.pk},
        )
        response = self.client.get(url, **self.header)
        self.assertStatus(response, status.HTTP_503_SERVICE_UNAVAILABLE)
        response = self.client.post(url, **self.header)
        self.assertStatus(response, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #19
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_import_peering_sessions(self):
        url = reverse(
            "peering-api:internetexchange-import-peering-sessions",
            kwargs={"pk": self.internet_exchange.pk},
        )
        response = self.client.post(url, **self.header)
        self.assertStatus(response, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #20
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_available_peers(self):
        url = reverse(
            "peering-api:internetexchange-available-peers",
            kwargs={"pk": self.internet_exchange.pk},
        )
        response = self.client.get(url, **self.header)
        self.assertStatus(response, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #21
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_poll_peering_sessions(self):
        url = reverse(
            "peering-api:bgpgroup-poll-peering-sessions",
            kwargs={"pk": self.bgp_group.pk},
        )
        response = self.client.post(url, **self.header)
        self.assertStatus(response, status.HTTP_503_SERVICE_UNAVAILABLE) 
Example #22
Source File: views.py    From cadasta-platform with GNU Affero General Public License v3.0 4 votes vote down vote up
def search(self, query_dsl):

        magic_word = ''
        if 'should' in query_dsl['query']['bool']:
            temp = query_dsl['query']['bool']['should'][0]
            magic_word = temp['multi_match']['query'].lower()
        if magic_word == 'error':
            return Response({}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        if magic_word == 'bulkerror' and self.bulk:
            return Response({}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        entities = []
        page = []
        if magic_word != 'none':
            project = Project.objects.get(id=self.kwargs['projectid'])
            locations = list(SpatialUnit.objects.filter(project=project))
            parties = list(Party.objects.filter(project=project))
            rels = list(TenureRelationship.objects.filter(project=project))
            resources = list(Resource.objects.filter(project=project))

            while (
                len(locations) + len(parties) + len(rels) + len(resources) > 0
            ):
                if len(locations) > 0:
                    entities.append(locations.pop(0))
                if len(parties) > 0:
                    entities.append(parties.pop(0))
                if len(rels) > 0:
                    entities.append(rels.pop(0))
                if len(resources) > 0:
                    entities.append(resources.pop(0))
                if magic_word == 'limited':
                    break

            start_idx = query_dsl.get('from', 0)
            end_idx = start_idx + query_dsl.get('size', 10)
            page = entities[start_idx:end_idx]

        if self.bulk:
            body = []
            for entity in page:
                body.extend(transform(entity, bulk=True))
            return HttpResponse(
                ''.join([json.dumps(line) + '\n' for line in body]),
                content_type="text/plain"
            )
        else:
            return Response({
                'hits': {
                    'total': len(entities),
                    'hits': [transform(entity) for entity in page],
                },
            }) 
Example #23
Source File: handlers.py    From product-definition-center with MIT License 4 votes vote down vote up
def exception_handler(exc, context):
    """
    This handler will overwrite rest framework default handler, additionally,
    it will process ValidationError (most of them were raised by
    django.db.models and django.forms), DB error (Refs PEP249).

    Show some details about the error, if it's safe. It could be more useful
    when the server does not work well in production env.

    Setting the `exception` attribute on the response is not necessary as it
    will be done by REST Framework.
    """
    response = views.exception_handler(exc, context)

    if response is None:
        if isinstance(exc, (exceptions.ValidationError, exceptions.FieldError)):
            # value is not correct or name is invalid.
            msg = exc.messages if hasattr(exc, 'messages') else str(exc)
            return Response({'detail': msg},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, exceptions.ObjectDoesNotExist):
            return Response({'detail': 'Not found:  %s' % str(exc)},
                            status=status.HTTP_404_NOT_FOUND)
        elif isinstance(exc, ProtectedError):
            return Response({"detail": "%s %s" % exc.args},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, ValueError):
            return Response({'detail': str(exc)},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, db.IntegrityError):
            # Refs PEP249
            # Maybe a duplicate PK, FK check fails, index conflict.
            return Response({'detail': str(exc)},
                            status=status.HTTP_409_CONFLICT)
        elif isinstance(exc, db.DatabaseError):
            # Refs PEP249
            # Other DB errors, such as incorrect grammar, transaction error etc.
            return Response({'detail': 'The database encountered an internal '
                                       'error or misconfiguration and was '
                                       'unable to complete your request.'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            logger = logging.getLogger(__name__)
            logger.error('Unhandled exception', exc_info=sys.exc_info())
            return Response(data=settings.INTERNAL_SERVER_ERROR_RESPONSE,
                            status=status.HTTP_503_SERVICE_UNAVAILABLE)
    return response 
Example #24
Source File: exception_handlers.py    From desec-stack with MIT License 4 votes vote down vote up
def exception_handler(exc, context):
    """
    desecapi specific exception handling. If no special treatment is applied,
    we default to restframework's exception handling. See also
    https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
    """

    def _perform_handling(name):
        logger = logging.getLogger('django.request')
        logger.error('{} Supplementary Information'.format(name),
                     exc_info=exc, stack_info=False)

        # Gracefully let clients know that we cannot connect to the database
        response =  Response({'detail': 'Please try again later.'},
                        status=status.HTTP_503_SERVICE_UNAVAILABLE)
        metrics.get('desecapi_database_unavailable').inc()
        return response

    # Catch DB exception and log an extra error for additional context
    if isinstance(exc, OperationalError):
        if isinstance(exc.args, (list, dict, tuple)) and exc.args and \
            exc.args[0] in (
                2002,  # Connection refused (Socket)
                2003,  # Connection refused (TCP)
                2005,  # Unresolved host name
                2007,  # Server protocol mismatch
                2009,  # Wrong host info
                2026,  # SSL connection error
        ):
            return _perform_handling('OperationalError')

    # OSError happens on system-related errors, like full disk or getaddrinfo() failure.
    # Catch it and log an extra error for additional context.
    if isinstance(exc, OSError):
        return _perform_handling('OSError')

    if isinstance(exc, UnsupportedRule):
        return _perform_handling('UnsupportedRule')

    if isinstance(exc, PDNSException):
        return _perform_handling('PDNSException')

    return drf_exception_handler(exc, context)