How to use the restless.http.HttpError function in restless

To help you get started, we’ve selected a few restless examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dobarkod / django-restless / testproject / testapp / views.py View on Github external
def authenticate(self, request):
        user = request.params.get('user')
        if user == 'friend':
            return None
        elif user == 'foe':
            return Http403('you shall not pass')
        elif user == 'exceptional-foe':
            raise HttpError(403, 'with exception')
        else:
            # this is an illegal return value for this function
            return 42
github opencivicdata / imago / imago / helpers.py View on Github external
if 'sort' in params:
            sort_by = params.pop('sort').split(",")

        fields = self.default_fields
        if 'fields' in params:
            fields = params.pop('fields').split(",")

        data = self.get_query_set(request, *args, **kwargs)
        data = self.filter(data, **params)
        data = self.sort(data, sort_by)
        data = data.distinct("id")

        try:
            related, config = get_fields(self.serialize_config, fields=fields)
        except FieldKeyError as e:
            raise HttpError(400, "Error: You've asked for a field ({}) that "
                            "is invalid. Valid fields are: {}".format(
                                e.field, ', '.join(self.serialize_config.keys())))
        except KeyError as e:
            raise HttpError(400, "Error: Invalid field: %s" % (e))

        data = data.prefetch_related(*related)

        try:
            data_page = self.paginate(data, page, per_page)
        except EmptyPage:
            raise HttpError(404, 'No such page (heh, literally - its out of bounds)')

        self.start_debug()

        count = data_page.paginator.count
github opencivicdata / imago / imago / helpers.py View on Github external
if 'fields' in params:
            fields = params.pop('fields').split(",")

        data = self.get_query_set(request, *args, **kwargs)
        data = self.filter(data, **params)
        data = self.sort(data, sort_by)
        data = data.distinct("id")

        try:
            related, config = get_fields(self.serialize_config, fields=fields)
        except FieldKeyError as e:
            raise HttpError(400, "Error: You've asked for a field ({}) that "
                            "is invalid. Valid fields are: {}".format(
                                e.field, ', '.join(self.serialize_config.keys())))
        except KeyError as e:
            raise HttpError(400, "Error: Invalid field: %s" % (e))

        data = data.prefetch_related(*related)

        try:
            data_page = self.paginate(data, page, per_page)
        except EmptyPage:
            raise HttpError(404, 'No such page (heh, literally - its out of bounds)')

        self.start_debug()

        count = data_page.paginator.count

        response = {
            "meta": {
                "count": len(data_page.object_list),
                "page": page,
github dobarkod / django-restless / restless / modelviews.py View on Github external
"""Return a QuerySet that this endpoint represents.

        If `model` class attribute is set, this method returns the `all()`
        queryset for the model. You can override the method to provide custom
        behaviour. The `args` and `kwargs` parameters are passed in directly
        from the URL pattern match.

        If the method raises a :py:class:`restless.http.HttpError` exception,
        the rest of the request processing is terminated and the error is
        immediately returned to the client.
        """

        if self.model:
            return self.model.objects.all()
        else:
            raise HttpError(404, 'Resource Not Found')
github opencivicdata / imago / imago / views.py View on Github external
def filter(self, data, **params):
        DATE_FORMAT = "%Y-%m-%d"
        today = datetime.datetime.strftime(datetime.datetime.now(), DATE_FORMAT)

        lat = params.get('lat')
        lon = params.get('lon')
        date = datetime.datetime.strptime(
            params.get('date', today), DATE_FORMAT).date()

        if params.get('date') and not (lat and lon):
            raise HttpError(400, "If date specified, must also provide lat & lon")

        if (lat and lon):
            data = data.filter(
                Q(geometries__boundary__set__start_date__lte=date) | Q(geometries__boundary__set__start_date=None),
                Q(geometries__boundary__set__end_date__gte=date) | Q(geometries__boundary__set__end_date=None),
                geometries__boundary__shape__contains='POINT({} {})'.format(lon, lat)
            )
        elif (lat and not lon) or (lon and not lat):
            raise HttpError(400, "Must specify lat & lon together")

        return data
github dobarkod / django-restless / restless / modelviews.py View on Github external
def put(self, request, *args, **kwargs):
        """Update the object represented by this endpoint."""

        if 'PUT' not in self.methods:
            raise HttpError(405, 'Method Not Allowed')

        Form = _get_form(self.form, self.model)
        instance = self.get_instance(request, *args, **kwargs)
        form = Form(request.data or None, request.FILES,
            instance=instance)
        if form.is_valid():
            obj = form.save()
            return Http200(self.serialize(obj))
        raise HttpError(400, 'Invalid data', errors=form.errors)
github dobarkod / django-restless / restless / modelviews.py View on Github external
def post(self, request, *args, **kwargs):
        """Create a new object."""

        if 'POST' not in self.methods:
            raise HttpError(405, 'Method Not Allowed')

        Form = _get_form(self.form, self.model)
        form = Form(request.data or None, request.FILES)
        if form.is_valid():
            obj = form.save()
            return Http201(self.serialize(obj))
            
        raise HttpError(400, 'Invalid Data', errors=form.errors)
github dobarkod / django-restless / restless / modelviews.py View on Github external
match.

        If the method raises a :py:class:`restless.http.HttpError` exception,
        the rest of the request processing is terminated and the error is
        immediately returned to the client.
        """

        if self.model and self.lookup_field in kwargs:
            try:
                return self.model.objects.get(**{
                    self.lookup_field: kwargs.get(self.lookup_field)
                })
            except self.model.DoesNotExist:
                raise HttpError(404, 'Resource Not Found')
        else:
            raise HttpError(404, 'Resource Not Found')
github dobarkod / django-restless / restless / http.py View on Github external
def __init__(self, code, reason, **additional_data):
        super(HttpError, self).__init__(self, reason)
        self.response = JSONErrorResponse(reason, **additional_data)
        self.response.status_code = code
github dobarkod / django-restless / restless / modelviews.py View on Github external
def post(self, request, *args, **kwargs):
        if 'POST' not in self.methods:
            raise HttpError(405, 'Method Not Allowed')

        instance = self.get_instance(request, *args, **kwargs)
        return self.action(request, instance, *args, **kwargs)