Ejemplo n.º 1
0
    def get_subcategory_detail(self, request, **kwargs):
        """Get the SubcategorySubmission for the Subcategory where
        id = kwargs['subcatpk']."""
        # Need to check SubcategorySubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in SubcategorySubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        subcategory_id = kwargs.pop('subcatpk')
        # Make sure the submission set is valid:
        basic_bundle = self.build_bundle(request=request)
        try:
            obj = self.cached_obj_get(bundle=basic_bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        kwargs['subcatpk'] = subcategory_id
        kwargs['submissionset'] = obj
        return SubcategorySubmissionResource().get_detail(request, **kwargs)
Ejemplo n.º 2
0
    def purchase(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        data = self.deserialize(request,
                                request.body,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))
        amount = data.get('amount', '')
        if not amount:
            return HttpBadRequest()

        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']},
                                       request=request)
            account = self.cached_obj_get(
                bundle=bundle, **self.remove_api_resource_names(kwargs))
            card_payment = PendingPayment.objects.currency_purchase(
                account, amount)

            return self.create_response(request, {
                'reference':
                card_payment.reference,
                'url':
                settings.BASESITE_URL +
                reverse('payments:payment_form',
                        kwargs={'uuid': card_payment.reference})
            },
                                        response_class=HttpCreated)

        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")
Ejemplo n.º 3
0
    def get_credit_detail(self, request, **kwargs):
        """Get the CreditSubmissionResource that matches the Credit
        where id = kwargs['credpk'] and the SubmissionSet where
        id = kwargs['pk'].
        """
        # Need to check CreditSubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in CreditSubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        credit_id = kwargs.pop('credpk')
        basic_bundle = self.build_bundle(request=request)
        try:
            submissionset = self.cached_obj_get(
                bundle=basic_bundle, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        kwargs.pop('pk')
        kwargs['credpk'] = credit_id
        kwargs['submissionset'] = submissionset
        credit_submission_resource = CreditSubmissionResource()
        detail = credit_submission_resource.get_detail(request, **kwargs)
        return detail
Ejemplo n.º 4
0
    def get_field_detail(self, request, **kwargs):
        """Given the id's of a SubmissionSet (kwargs['pk']) and
        a DocumentationField (kwargs['fieldpk']), get the
        DocumentationFieldSubmissionResource that matches.
        """
        # Need to check
        # DocumentationFieldSubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above bypasses the
        # usual check:
        if (request.method.lower() not in
                DocumentationFieldSubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        for field_resource_type in (
                NumericSubmissionResource, TextSubmissionResource,
                NumericSubmissionResource, TextSubmissionResource,
                LongTextSubmissionResource, DateSubmissionResource,
                URLSubmissionResource, UploadSubmissionResource,
                BooleanSubmissionResource, ChoiceSubmissionResource,
                MultiChoiceSubmissionResource):
            resources = field_resource_type().obj_get_list(
                request, submissionset_id=kwargs['pk'])
            try:
                resources.get(documentation_field__id=kwargs['fieldpk'])
                break
            except ObjectDoesNotExist:
                pass
        else:
            return HttpGone()

        kwargs['submissionset_id'] = kwargs.pop('pk')
        field_submission_resource = field_resource_type()
        detail = field_submission_resource.get_detail(request, **kwargs)
        return detail
Ejemplo n.º 5
0
    def feed_content(self, request, **kwargs):

        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)

        try:
            stream = Stream.objects.get(id=kwargs['pk'])
        except Stream.DoesNotExist:
            return HttpGone()

        content = get_retrieve_content(stream.url)

        feed = get_feed_data(content)
        feed = prepare_feed(feed,
                            upscaled_items=['channel'],
                            remove_items=[
                                'link', 'image', 'language', 'copyright',
                                'guid',
                                '{http://purl.org/dc/elements/1.1/}creator'
                            ])

        content = {'feed': feed}

        connection.close()
        return self.create_response(request, content)
Ejemplo n.º 6
0
    def invite(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        data = self.deserialize(request,
                                request.body,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))
        email = data.get('email', '')
        if not email:
            return HttpBadRequest()

        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']},
                                       request=request)
            account = self.cached_obj_get(
                bundle=bundle, **self.remove_api_resource_names(kwargs))
            invite = GuestInvitation.objects.invite_user(account=account,
                                                         email=email)

            return self.create_response(request, {'token': invite.token},
                                        response_class=HttpCreated)

        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")
Ejemplo n.º 7
0
 def test_various_statuses(self):
     created = HttpCreated(location='http://example.com/thingy/1/')
     self.assertEqual(created.status_code, 201)
     self.assertEqual(created['Location'], 'http://example.com/thingy/1/')
     # Regression.
     created_2 = HttpCreated()
     self.assertEqual(created_2.status_code, 201)
     self.assertEqual(created_2['Location'], '')
     accepted = HttpAccepted()
     self.assertEqual(accepted.status_code, 202)
     no_content = HttpNoContent()
     self.assertEqual(no_content.status_code, 204)
     see_other = HttpSeeOther()
     self.assertEqual(see_other.status_code, 303)
     not_modified = HttpNotModified()
     self.assertEqual(not_modified.status_code, 304)
     bad_request = HttpBadRequest()
     self.assertEqual(bad_request.status_code, 400)
     unauthorized = HttpUnauthorized()
     self.assertEqual(unauthorized.status_code, 401)
     not_found = HttpNotFound()
     self.assertEqual(not_found.status_code, 404)
     not_allowed = HttpMethodNotAllowed()
     self.assertEqual(not_allowed.status_code, 405)
     conflict = HttpConflict()
     self.assertEqual(conflict.status_code, 409)
     gone = HttpGone()
     self.assertEqual(gone.status_code, 410)
     toomanyrequests = HttpTooManyRequests()
     self.assertEqual(toomanyrequests.status_code, 429)
     not_implemented = HttpNotImplemented()
     self.assertEqual(not_implemented.status_code, 501)
Ejemplo n.º 8
0
    def get_grafana_line(self, request, **kwargs):
        self.method_check(request, allowed=['get', 'options'])
        self.is_authenticated(request)

        response = HttpResponse()
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Headers'] = 'Content-Type'

        if request.method == 'options':
            return response

        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']},
                                       request=request)
            obj = self.cached_obj_get(bundle=bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        response.content = '<h2>{}</h2><span>FDID: {} STATE: {} POPULATION: {}</span>'.format(
            obj.name, obj.fdid, obj.state, obj.population)
        return response
Ejemplo n.º 9
0
    def get_children(self, request, **kwargs):
        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request)
            obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices("More than one resource is found at this URI")

        child_resource = Facebook_Status_CommentResource()
        return child_resource.get_list(request, parent_id=obj.pk)
Ejemplo n.º 10
0
    def set_active(self, active, request, **kwargs):
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        self.throttle_check(request)
        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']},
                                       request=request)
            app = self.cached_obj_get(bundle=bundle,
                                      **self.remove_api_resource_names(kwargs))
            app.config.active = active
            app.apps_config.save()
        except ObjectDoesNotExist:
            return HttpGone()

        self.log_throttled_access(request)
        return self.create_response(request, {'success': True})
Ejemplo n.º 11
0
    def get_offers(self, request, **kwargs):

        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']},
                                       request=request)
            obj = self.cached_obj_get(bundle=bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        offers = OffersResource()
        return offers.get_list(request, entity=obj.pk)
Ejemplo n.º 12
0
 def remove_children(self, request, **kwargs):
     try:
         obj = self.cached_obj_get(request=request,
                                   **self.remove_api_resource_names(kwargs))
     except ObjectDoesNotExist:
         return HttpGone()
     except MultipleObjectsReturned:
         return HttpMultipleChoices("More than one resource "
                                    "is found at this URI.")
     if request.method == 'POST':
         data = json.loads(request.POST.items()[0][0])
         if 'image' in data:
             if isinstance(data['image'], list):
                 for URI in data['image']:
                     try:
                         im = Image.objects.get(
                             uuid=uuid_re.search(URI).group()
                         )
                         obj.image_set.remove(im)
                     except ObjectDoesNotExist:
                         return HttpResponseNotFound(
                             'At least one of the image '
                             'URI\'s cannot be found')
             else:
                 raise ImmediateHttpResponse(response=HttpForbidden(
                     'Image URI\'s must be in an array'))
         if 'wordbox' in data:
             if isinstance(data['wordbox'], list):
                 for URI in data['wordbox']:
                     try:
                         wb = WordBox.objects.get(uuid=uuid_re.search(
                             URI).group())
                         obj.wordbox_set.remove(wb)
                     except ObjectDoesNotExist:
                         return HttpResponseNotFound(
                             'At least one of the wordbox '
                             'URI\'s cannot be found')
             else:
                 raise ImmediateHttpResponse(response=HttpForbidden(
                     'Wordbox URI\'s must be in an array'))
     else:
         raise ImmediateHttpResponse(response=HttpResponse(status=405))
     return HttpCreated()
Ejemplo n.º 13
0
    def handle_nested(self, request, **kwargs):
        resource_name = kwargs.pop('nest_resource')
        resource = self.fields[resource_name].to_class().__class__

        try:
            stripped_kwargs = self.remove_api_resource_names(kwargs)
            obj = self.cached_obj_get(request=request, **stripped_kwargs)
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices('Multiple objects with this PK.')

        r = resource()
        if request.method.lower() == 'get':
            return r.get_list(request, report=obj.pk)
        elif request.method.lower() == 'post':
            cont_type = request.META.get('CONTENT_TYPE', 'application/json')
            deserialized = r.deserialize(request, format=cont_type)

            report_uri = ReportResource().get_resource_uri(obj)
            user_uri = UserResource().get_resource_uri(request.user)

            parms = {'report': report_uri, 'user': user_uri}
            if 'form' in cont_type:
                deserialized = dict(
                        (str(k), v[0] if (type(v)==list and len(v)>0) else v) \
                                for k, v in deserialized.iteritems())
            parms.update(deserialized)
            try:
                bundle = r.build_bundle(data=dict_strip_unicode_keys(parms),
                                        request=request)
                r.is_valid(bundle, request)
                r.obj_create(bundle)  # this creates the actual child
            except:
                raise ValueError(parms)
            bundle_dehyd = r.full_dehydrate(bundle)
            resp = r.create_response(request, bundle_dehyd)
            resp['location'] = r.get_resource_uri(bundle)
            resp.status_code = 201
            return resp
        else:
            raise NotImplementedError('In POST and GET we trust.')
Ejemplo n.º 14
0
    def cancel_payment(self, request, **kwargs):

        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        self.throttle_check(request)

        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']},
                                       request=request)
            payment = self.cached_obj_get(
                bundle=bundle, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")
        payment.cancel_payment()
        return self.create_response(request,
                                    bundle,
                                    response_class=HttpCreated)
Ejemplo n.º 15
0
    def wallet_purchase(self, request, **kwargs):

        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        self.throttle_check(request)

        data = self.deserialize(request,
                                request.body,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))
        bundle = self.build_bundle(data=data, request=request)
        amount = data.get('amount', None)

        if not amount:
            return HttpGone()

        user_wallet = self.obj_get(bundle)
        bundle.obj = Wallet.debit_transaction(user_wallet, amount)

        return self.create_response(request,
                                    bundle,
                                    response_class=HttpCreated)
Ejemplo n.º 16
0
    def get_category_list(self, request, **kwargs):
        """Get a list of categories for the SubmissionSet with
        id = kwargs['pk']."""
        # Need to check CategorySubmissionResource.Meta.allowed_methods
        # explicitly because the URL fiddling done above
        # bypasses the usual check:
        if (request.method.lower()
                not in CategorySubmissionResource.Meta.allowed_methods):
            return HttpMethodNotAllowed()
        self.is_authenticated(request)
        basic_bundle = self.build_bundle(request=request)
        try:
            obj = self.cached_obj_get(bundle=basic_bundle,
                                      **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        category_submission_resource = CategorySubmissionResource()
        return category_submission_resource.get_list(request,
                                                     submissionset=obj.pk)
Ejemplo n.º 17
0
 def get_relationships(self, request, **kwargs):
     rel_type = kwargs.get('rel_type', None)
     if rel_type:
         kwargs.pop('rel_type', None)
     try:
         data = {'pk': kwargs['pk']}
         if getattr(self._meta, 'pk_field', 'pk') != 'pk':
             kwargs[self._meta.pk_field] = kwargs['pk']
             data = {self._meta.pk_field: kwargs['pk']}
             kwargs.pop('pk', None)
         bundle = self.build_bundle(data, request=request)
         obj = self.cached_obj_get(bundle=bundle,
                                   **self.remove_api_resource_names(kwargs))
         kwargs = {'parent_obj': obj.pk}
     except ObjectDoesNotExist:
         return HttpGone()
     except MultipleObjectsReturned:
         return HttpMultipleChoices(
             "More than one resource is found at this URI.")
     if rel_type:
         kwargs['rel_type'] = rel_type
     child_resource = RelationshipResource()
     return child_resource.get_list(request, **kwargs)