Beispiel #1
0
    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
Beispiel #2
0
    def get(self, request, pk, *args, **kwargs):
        params = request.params

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

        related, config = get_fields(self.serialize_config, fields=fields)

        self.start_debug()

        try:
            obj = self.model.objects.prefetch_related(*related).get(pk=pk)
        except ObjectDoesNotExist as e:
            raise HttpError(404, "Error: {}".format(e))
        except Exception:
            raise HttpError(500,
                            "Error: Something went wrong with your request")

        serialized = serialize(obj, **config)
        serialized['debug'] = self.get_debug()

        response = Http200(serialized)
        response['Access-Control-Allow-Origin'] = "*"

        return response
Beispiel #3
0
    def filter(self, data, **kwargs):
        """
        Filter the Django query set.

        THe kwargs will be unpacked into Django directly, letting you
        use full Django query syntax here.
        """
        kwargs = self.adjust_filters(kwargs)
        try:
            return data.filter(**kwargs)
        except FieldError:
            raise HttpError(
                400, "Error: You've passed an invalid filter parameter.")
        except Exception:
            raise HttpError(500,
                            "Error: Something went wrong with your request")
Beispiel #4
0
 def adjust_filters(self, params):
     lat = params.pop('lat', None)
     lon = params.pop('lon', None)
     if lat and lon:
         params['geometries__boundary__shape__contains'] = 'POINT({} {})'.format(lon, lat)
     elif lat or lon:
         raise HttpError(400, "must specify lat & lon together")
     return params
Beispiel #5
0
    def _(self, request, *args, **kwargs):
        if no_authentication_or_is_authenticated(request):
            if 'apikey' in request.params:
                request.params.pop('apikey')

            return fn(self, request, *args, **kwargs)
        else:
            raise HttpError(
                403, "Authorization Required: obtain a key at " +
                settings.LOCKSMITH_REGISTRATION_URL)
 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
 def post(self, request, *args, **kwargs):
     data = json.loads(request.body.decode('utf-8'))
     qs = Geomodeldiff.objects.filter(key=data['key'],
                                      key_id=data['key_id'])
     if qs.count() == 0:
         obj = Geomodeldiff(**data)
         try:
             obj.save()
             return Http201(self.serialize(obj))
         except:
             raise HttpError(400, 'Invalid Data')
     else:
         print('Already exists!')
         print('key=%s, key_id=%s' % (data['key'], data['key_id']))
         return Http200('Already exists!')
    def get_query_set(self, request, *args, **kwargs):
        last_id = request.GET.get('last_id', 0)
        try:
            last_id = int(last_id)
        except Exception:
            last_id = 0
        limit = request.GET.get('limit', 0)
        try:
            limit = int(limit)
        except Exception:
            limit = 0

        if self.model:
            queryset = (self.model.objects.all().filter(
                key=settings.MODELDIFF_KEY).filter(
                    pk__gt=last_id).order_by('id'))
            if limit > 0:
                queryset = queryset[:limit]
            return queryset
        else:
            raise HttpError(404, 'Resource Not Found')
Beispiel #9
0
    def get(self, request, *args, **kwargs):
        """
        Default 'GET' class-based view.
        """

        params = request.params

        # default to page 1
        page = int(params.pop('page', 1))
        per_page = min(self.max_per_page,
                       int(params.pop('per_page', self.max_per_page)))

        sort_by = []
        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)

        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,
                "per_page": per_page,
                "max_page": math.ceil(count / per_page),
                "total_count": count,
            },
            "results": [serialize(x, **config) for x in data_page.object_list]
        }

        if settings.DEBUG:
            response['debug'] = self.get_debug()
            response['debug'].update({
                "prefetch_fields": list(related),
                "page": page,
                "sort": sort_by,
                "field": fields,
            })

        response = Http200(response)

        response['Access-Control-Allow-Origin'] = "*"
        return response
Beispiel #10
0
 def get(self, request):
     raise HttpError(400, 'raised error', extra_data='foo')