def get_detail(self, request, **kwargs): """ Returns a single serialized resource. Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result set and serializes it. Should return a HttpResponse (200 OK). """ try: # If call was made through Nested we should already have the # child object. if 'child_object' in kwargs: obj = kwargs.pop('child_object', None) if obj is None: return http.HttpNotFound() else: obj = self.cached_obj_get( request=request, **self.remove_api_resource_names(kwargs)) except AttributeError: return http.HttpNotFound() except ObjectDoesNotExist: return http.HttpNotFound() except MultipleObjectsReturned: return http.HttpMultipleChoices("More than one resource is found " "at this URI.") bundle = self.build_bundle(obj=obj, request=request) bundle = self.full_dehydrate(bundle) bundle = self.alter_detail_data_to_serialize(request, bundle) return self.create_response(request, bundle)
def obj_create(self, bundle, **kwargs): story_id = kwargs.get('story_id') asset_id = kwargs.get('asset_id') if asset_id: try: asset = Asset.objects.get(asset_id=asset_id) if not asset.has_perm(bundle.request.user, 'change'): raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the asset matching the provided asset ID")) except ObjectDoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound("An asset matching the provided asset ID could not be found")) elif story_id: try: story = Story.objects.get(story_id=story_id) if not story.has_perm(bundle.request.user, 'change'): raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the story matching the provided story ID")) except ObjectDoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound("A story matching the provided story ID could not be found")) # Set the asset's owner to the request's user if bundle.request.user: kwargs['owner'] = bundle.request.user # Let the superclass create the object bundle = super(DataSetResource, self).obj_create( bundle, **kwargs) if asset_id: asset.datasets.add(bundle.obj) elif story_id: # Associate the newly created dataset with the story story.datasets.add(bundle.obj) return bundle
def render_png(self, obj, size, engine, ignoreCoords): molstring = obj.molecule.compoundstructures.molfile smarts = obj.alert.smarts ret = None if engine == 'rdkit': fontSize = int(size / 33) if size < 200: fontSize = 1 options.atomLabelFontSize = fontSize highlight = highlight_substructure_rdkit(molstring, smarts) if not highlight: raise ImmediateHttpResponse(response=http.HttpNotFound()) mol, matching = highlight ret = render_rdkit(mol, matching, options, 'png', size, False, ignoreCoords) elif engine == 'indigo': mol = highlight_substructure_indigo(molstring, smarts) if not mol: raise ImmediateHttpResponse(response=http.HttpNotFound()) ret = render_indigo(mol, options, 'png', 10, size, False, ignoreCoords) return ret, "image/png"
def delete_related_detail(self, request, **kwargs): bundle = Bundle(request=request) dataset_id = kwargs.get('dataset_id') story_id = kwargs.pop('story_id', None) asset_id = kwargs.pop('asset_id', None) if asset_id: try: asset = Asset.objects.get(asset_id=asset_id) if not asset.has_perm(bundle.request.user, 'change'): raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the asset matching the provided asset ID")) except ObjectDoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound("An asset matching the provided asset ID could not be found")) elif story_id: try: story = Story.objects.get(story_id=story_id) if not story.has_perm(bundle.request.user, 'change'): raise ImmediateHttpResponse(response=http.HttpUnauthorized("You are not authorized to change the story matching the provided story ID")) except ObjectDoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound("A story matching the provided story ID could not be found")) self.obj_get(bundle, dataset_id=dataset_id) if asset_id: asset.datasets.remove(bundle.obj) elif story_id: story.datasets.remove(bundle.obj) return http.HttpNoContent()
def build_filters(self, filters=None): if filters is None: filters = {} orm_filters = super(BrandResource, self).build_filters( filters) # modify super(*,self) if filters: # check if dictionary is empty or not try: if "owner" in filters: obj = UserProfile.objects.get( uuid=uuid_re.search(filters['owner']).group()) if 'owner__exact' in orm_filters: # delete this field since this is a GFK del orm_filters['owner__exact'] else: raise ImmediateHttpResponse( response=http.HttpNotFound()) else: return orm_filters if not obj.is_active: return orm_filters sqs = obj.brand_set.filter(is_active=True) orm_filters["pk__in"] = [i.pk for i in sqs] except Brand.DoesNotExist: orm_filters["pk__in"] = [] # return HttpGone() except Brand.MultipleObjectsReturned: # return HttpMultipleChoices("More than one resource is found " # "at this URI.") orm_filters["pk__in"] = [] raise ImmediateHttpResponse(response=http.HttpNotFound()) return orm_filters
def get_object_or_404(cls, **filters): """ A wrapper around our more familiar get_object_or_404, for when we need to get access to an object that isn't covered by get_obj. """ if not filters: raise ImmediateHttpResponse(response=http.HttpNotFound()) try: return cls.objects.get(**filters) except (cls.DoesNotExist, cls.MultipleObjectsReturned): raise ImmediateHttpResponse(response=http.HttpNotFound())
def obj_create(self, bundle, request=None, **kwargs): try: userProfile = User.objects.get( pk=bundle.request.user.id).get_profile() except: raise ImmediateHttpResponse(response=http.HttpNotFound()) try: obj = self.fields['parent'].build_related_resource( bundle.data['parent']).obj except: raise ImmediateHttpResponse(response=http.HttpNotFound()) if obj.vote_set.filter(owner_id=userProfile.pk).exists(): bundle.obj = obj.vote_set.get(owner_id=userProfile.pk) if bundle.obj.is_active is not True: bundle.obj.IPaddress = bundle.request.META['REMOTE_ADDR'] bundle.obj.is_active = True bundle.obj.created_time = now() else: bundle.obj.parent = obj bundle.obj.IPaddress = bundle.request.META['REMOTE_ADDR'] bundle.obj.owner = userProfile if hasattr(bundle.obj, 'total_votes'): bundle.obj.total_votes = bundle.obj.total_votes() bundle.obj.save() # email owner of the image that this vote modifies if bundle.obj.parent.obj_type() == 'image': parent_owner = bundle.obj.parent.owner vote_owner = bundle.obj.owner if parent_owner != vote_owner: media_url = u'{page_base_url}image/{uuid}'.format( page_base_url=PAGE_BASE_URL, uuid=bundle.obj.parent.uuid) vote_owner_url = u'{base_url}{vote_owner}'.format( base_url=BASE_URL, vote_owner=vote_owner.username) # send email to the owner of the image send_mail( u'Dujour: New vote on your photo!', u'Hi {parent_owner}!\n\n'.format( parent_owner=parent_owner.first_name) + u'{vote_owner} voted on your photo at' u'{media_url}.\n\n'.format( vote_owner=vote_owner.first_name, media_url=media_url) + u'Take a look at {vote_owner}\'s profile here:' u'{vote_owner_url}\n\n'.format( vote_owner=vote_owner.first_name, vote_owner_url=vote_owner_url) + u'- Dujour Team', u'*****@*****.**', [str(parent_owner.email)], fail_silently=False) return bundle
def get_groups(self, request, **kwargs): # from app.detective.utils import dumb_profiler # import time # dumb_profiler.dispatch_time = time.time() # db_start = time.time() 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 User.DoesNotExist: return http.HttpNotFound("User not found") user = bundle.request.user group_resource = GroupResource() groups = group_resource.obj_get_list(bundle).filter(Q(user__id=obj.id)).exclude(topic__pk=None) if not user or not user.is_staff: if user: read_perms = [perm.split('.')[0] for perm in user.get_all_permissions() if perm.endswith(".contribute_read")] read_perms = [perm for vector in [[perm + '_contributor', perm + '_administrator'] for perm in read_perms] for perm in vector] q_filter = Q(topic__public=True) | Q(name__in=read_perms) else: q_filter = Q(topic__public=True) groups = groups.filter(q_filter) # dumb_profiler.db_time = time.time() - db_start limit = int(request.GET.get('limit', 20)) paginator = Paginator(groups, limit) objects = [] # serializer_start = time.time() try: p = int(request.GET.get('page', 1)) page = paginator.page(p) for group in page.object_list: bundle = group_resource.build_bundle(obj=group, request=request) bundle = group_resource.full_dehydrate(bundle) objects.append(bundle) except InvalidPage: # Allow empty page pass object_list = { 'objects': objects, 'meta': { 'page': p, 'limit': limit, 'total_count': paginator.count } } response = group_resource.create_response(request, object_list) # dumb_profiler.serializer_time = time.time() - serializer_start return response
def preprocess_filters(self, filters, for_cache_key=False): ret = {} for filter_expr, value in list(filters.items()): filter_bits = filter_expr.split(LOOKUP_SEP) if filter_expr == 'similarity': continue if len(filter_bits) and filter_bits[-1] == 'flexmatch': if not value.strip(): raise BadRequest("Input string is empty") if value.upper().startswith('CHEMBL'): try: mol = MoleculeDictionary.objects.get( chembl_id=value.upper()) smiles = mol.compoundstructures.canonical_smiles value = smiles except ObjectDoesNotExist: raise ImmediateHttpResponse( response=http.HttpNotFound()) if not for_cache_key: molecule_chembl_ids_flexmatch = self.elastic_search_flexmatch( value) ret["molecule_chembl_id__in"] = molecule_chembl_ids_flexmatch continue ret[filter_expr] = value return ret
def export_entries(self, request, serializer_slug, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) try: serializer = self.get_serializer(serializer_slug)() if not hasattr(serializer, 'serialize'): raise export_objects = self.get_object_list(request) if not export_objects: return http.HttpNotFound() exported_buffer, filename = self.do_export( request, serializer, export_objects=export_objects) if isinstance(exported_buffer, HttpResponse): return exported_buffer except Exception as e: raise BadRequest('Can\'t export. %s' % e) self.log_throttled_access(request) response = HttpResponse(exported_buffer, content_type=serializer.type_mime[0]) response[ 'Content-Disposition'] = 'attachment; filename="%s"' % urlquote( '.'.join([filename, serializer.type_ext])) return response
def build_filters(self, filters=None): if filters is None: filters = {} orm_filters = super(CommentResource, self).build_filters( filters) # modify super(*,self) if 'parent__exact' in orm_filters: del orm_filters['parent__exact'] # delete this field since this is a GFK # else: # raise ImmediateHttpResponse(response=http.HttpNotFound()) if "parent" in filters: try: obj = self.fields['parent'].build_related_resource( filters['parent']).obj if not obj.is_active: raise NotFound("Parent object does not exist") sqs = obj.comment_set.filter(is_active=True) orm_filters["pk__in"] = [i.pk for i in sqs] except Comment.DoesNotExist: orm_filters["pk__in"] = [] # return HttpGone() except Comment.MultipleObjectsReturned: orm_filters["pk__in"] = [] # return HttpMultipleChoices("More than one resource is found " # "at this URI.") raise ImmediateHttpResponse(response=http.HttpNotFound()) return orm_filters
def get_detail_impl(self, request, basic_bundle, **kwargs): """ Returns a single serialized resource. Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result set and serializes it. Should return a HttpResponse (200 OK). """ try: obj, in_cache = self.cached_obj_get_list( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) objects = obj.get('target_relations', []) except ObjectDoesNotExist: return http.HttpNotFound() if len(objects) == 1: object = objects[0] bundle = self.build_bundle(obj=object, request=request) bundle = self.full_dehydrate(bundle, **kwargs) bundle = self.alter_detail_data_to_serialize(request, bundle) return self.create_response(request, bundle) else: bundles = [] for ob in obj[self._meta.collection_name]: bundle = self.build_bundle(obj=ob, request=request) bundles.append( self.full_dehydrate(bundle, for_list=True, **kwargs)) obj[self._meta.collection_name] = bundles obj = self.alter_list_data_to_serialize(request, obj) return obj, in_cache
def _safe_get(self, bundle, **kwargs): filters = self.remove_api_resource_names(kwargs) try: return self.parent.cached_obj_get(bundle=bundle, **filters) except (queryset.DoesNotExist, exceptions.ObjectDoesNotExist): raise tastypie_exceptions.ImmediateHttpResponse(response=http.HttpNotFound())
def build_filters(self, filters=None): if filters is None: filters = {} orm_filters = super(ImageResource, self).build_filters( filters) # modify super(*,self) orm_filters = {} if filters: # check if dictionary is empty or not try: if "collection" in filters: obj = Collection.objects.get(uuid=uuid_re.search( filters['collection']).group()) elif "owner" in filters: obj = UserProfile.objects.get(uuid=uuid_re.search( filters['owner']).group()) elif "community" in filters: obj = Community.objects.get(uuid=uuid_re.search( filters['community']).group()) else: return orm_filters if not obj.is_active: return orm_filters sqs = obj.image_set.filter(is_active=True) orm_filters["pk__in"] = [i.pk for i in sqs] except Image.DoesNotExist: orm_filters["pk__in"] = [] # return HttpGone() except Image.MultipleObjectsReturned: orm_filters["pk__in"] = [] # return HttpMultipleChoices("More than one resource is found " # "at this URI.") raise ImmediateHttpResponse(response=http.HttpNotFound()) return orm_filters
def get_detail(self, request, **kwargs): """ Returns a single serialized resource. Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result set and serializes it. Should return a HttpResponse (200 OK). """ basic_bundle = self.build_bundle(request=request) try: obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except (ObjectDoesNotExist, NotFound): return http.HttpNotFound() except MultipleObjectsReturned: return http.HttpMultipleChoices( "More than one resource is found at this URI.") bundle = self.build_bundle(obj=obj, request=request) # add metadata to bundle to keep track of "depth", "ancestor" and "full" info bundle.related_info = bundle_related_data_info_factory(request=request) # end add bundle = self.full_dehydrate(bundle) bundle = self.alter_detail_data_to_serialize(request, bundle) return self.create_response(request, bundle)
def activate(self, request, **kwargs): try: self.validate_request(request.GET, ['token']) token = request.GET.get("token", None) # Make sure the key we're trying conforms to the pattern of a # SHA1 hash; if it doesn't, no point trying to look it up in # the database. if SHA1_RE.search(token): profile = RegistrationProfile.objects.get(activation_key=token) if not profile.activation_key_expired(): user = profile.user user.is_active = True user.save() profile.activation_key = RegistrationProfile.ACTIVATED profile.save() return self.create_response(request, { "success": True }) else: return http.HttpForbidden('Your activation token is no longer active or valid') else: return http.HttpForbidden('Your activation token is no longer active or valid') except RegistrationProfile.DoesNotExist: return http.HttpNotFound('Your activation token is no longer active or valid') except MalformedRequestError as e: return http.HttpBadRequest("%s as request GET parameters" % e)
def get_experiments(self, request, pk=None, **kwargs): if pk: try: sample_obj = Sample.objects.get(pk=pk) except ObjectDoesNotExist: return http.HttpNotFound() else: return http.HttpNotFound() objects = [] er = ExperimentResource() for e in sample_obj.experiments.all(): bundle = er.build_bundle(obj=e, request=request) bundle = er.full_dehydrate(bundle) objects.append(bundle) return self.create_response(request, objects)
def post_zip(self, request, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) try: event_obj = Event.objects.get(pk=kwargs['pk']) cont = rackspace.cloud_files.get_container( event_obj.container_name) album_zip = cont.get_object('{}.zip'.format(event_obj.uuid)) response_body = { 'zip_url': event_obj.zip_download_url, 'created_at': album_zip.last_modified + "Z", } return self.create_response(request, response_body) except ObjectDoesNotExist: return http.HttpNotFound() except MultipleObjectsReturned: return http.HttpMultipleChoices( "More than one resource is found at this URI.") else: # check if there's already a job running that is creating an album archive if app.backend.get('event:{0}:create_album_zip'.format( kwargs['pk'])): http409 = http.HttpResponse http409.status_code = 409 return http409() else: event.create_album_zip.delay(kwargs['pk']) return http.HttpAccepted()
def mark_as_state(self, request, invoicebase_state, **kwargs): """Set state for an InvoiceBase.""" self.method_check(request, allowed=['put']) self.is_authenticated(request) self.throttle_check(request) try: bundle = self.build_bundle(request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return http.HttpNotFound() try: previous_state, new_state = obj.set_state( invoicebase_state.upper(), issuer=request.vosae_user) invoicing_signals.post_client_changed_invoice_state.send( obj.__class__, issuer=request.vosae_user, document=obj, previous_state=previous_state) except (obj.InvalidState, InvalidInvoiceBaseState) as e: raise BadRequest(e) self.log_throttled_access(request) return http.HttpNoContent()
def make_invoice(self, request, **kwargs): """Create an invoice from a quotation/purchase order""" from invoicing.api.resources.invoice import InvoiceResource self.method_check(request, allowed=['put']) self.is_authenticated(request) self.throttle_check(request) try: bundle = self.build_bundle(request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return http.HttpNotFound() invoice = obj.make_invoice(request.vosae_user) invoicing_signals.post_make_invoice.send(obj.__class__, issuer=request.vosae_user, document=obj, new_document=invoice) invoice_resource = InvoiceResource() invoice_resource_bundle = invoice_resource.build_bundle( obj=invoice, request=request) self.log_throttled_access(request) to_be_serialized = { 'invoice_uri': invoice_resource.get_resource_uri(invoice_resource_bundle) } to_be_serialized = self.alter_list_data_to_serialize( request, to_be_serialized) return self.create_response(request, to_be_serialized)
def generate_pdf(self, request, **kwargs): """Generate a PDF""" self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) try: bundle = self.build_bundle(request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return http.HttpNotFound() try: language = request.META.get('HTTP_X_REPORT_LANGUAGE', None) if language is not None: assert language in [k[0] for k in settings.LANGUAGES] except: raise BadRequest('Invalid language parameters.') try: pdf = obj.get_pdf(issuer=request.vosae_user, language=language) pdf_resource = VosaeFileResource() pdf_resource_bundle = pdf_resource.build_bundle(obj=pdf, request=request) except Exception, e: print e raise BadRequest('Can\'t generate PDF. Verify parameters.')
def invoice_cancel(self, request, **kwargs): """Cancel the invoice and returns the associated credit note.""" from invoicing.api.resources.credit_note import CreditNoteResource self.method_check(request, allowed=['put']) self.is_authenticated(request) self.throttle_check(request) try: bundle = self.build_bundle(request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return http.HttpNotFound() try: credit_note = obj.cancel(request.vosae_user) invoicing_signals.post_cancel_invoice.send(obj.__class__, issuer=request.vosae_user, document=obj, credit_note=credit_note) credit_note_resource = CreditNoteResource() credit_note_resource_bundle = credit_note_resource.build_bundle(obj=credit_note, request=request) except NotCancelableInvoice as e: raise BadRequest(e) self.log_throttled_access(request) to_be_serialized = { 'credit_note_uri': credit_note_resource.get_resource_uri(credit_note_resource_bundle) } to_be_serialized = self.alter_list_data_to_serialize(request, to_be_serialized) return self.create_response(request, to_be_serialized)
def export_entry(self, request, serializer_slug, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) try: bundle = self.build_bundle(request=request) obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return http.HttpNotFound() try: serializer = self.get_serializer(serializer_slug)() export_objects = [obj] exported_buffer, filename = self.do_export( request, serializer, export_objects=export_objects) if isinstance(exported_buffer, HttpResponse): return exported_buffer except Exception as e: raise BadRequest('Can\'t export. %s' % e) self.log_throttled_access(request) response = HttpResponse(exported_buffer, content_type=serializer.type_mime[0]) response[ 'Content-Disposition'] = 'attachment; filename="%s"' % urlquote( '.'.join([filename, serializer.type_ext])) return response
def get_version(self, request, **kwargs): """ Returns the object resource detail with fields as they were at a certain version. """ obj = self._version_checks(request, **kwargs) q = { "object_id": obj.pk, "content_type__model": obj._meta.model_name, "content_type__app_label": obj._meta.app_label, "id": kwargs["version_id"], } try: ver = reversion.models.Version.objects.get(**q) except ObjectDoesNotExist: return http.HttpNotFound("Version not found") vobj = ver.object_version.object # fixme: lame attempt to fill in inherited fields when model # uses table inheritance for f, v in ver.field_dict.items(): try: setattr(vobj, f, v) except: pass # lame bundle = self.build_bundle(obj=vobj, request=request) bundle = self.full_dehydrate(bundle) bundle = self.alter_detail_data_to_serialize(request, bundle) return self.create_response(request, bundle)
def obj_create(self, bundle, request=None, **kwargs): story_id = kwargs.get('story_id') if story_id: try: story = Story.objects.get(story_id=story_id) if not story.has_perm(request.user, 'change'): raise ImmediateHttpResponse(response=http.HttpUnauthorized( "You are not authorized to change the story matching the provided story ID" )) except ObjectDoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound( "A story matching the provided story ID could not be found" )) # Set the asset's owner to the request's user if request.user: kwargs['owner'] = request.user # Let the superclass create the object bundle = super(LocationResource, self).obj_create(bundle, request, **kwargs) if story_id: # Associate the newly created object with the story story.locations.add(bundle.obj) story.save() return bundle
def patch_detail(self, request, **kwargs): request = convert_post_to_patch(request) try: obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return http.HttpNotFound() except MultipleObjectsReturned: return http.HttpMultipleChoices('More than one resource' 'is found at this URI.') bundle = self.build_bundle(obj=obj, request=request) bundle = self.full_dehydrate(bundle) bundle = self.alter_detail_data_to_serialize(request, bundle) # Now update the bundle in-place. deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get( 'CONTENT_TYPE', 'application/json')) # In case of a patch modification, we need to store # the initial values for the given object to check # the Etag header. request.initial_etag = bundle.obj.etag return self.create_patch_response(request, bundle, deserialized)
def obj_update(self, bundle, request, **kwargs): data = bundle.data try: obj = self.get_object_list(bundle.request).get(**kwargs) except Webapp.DoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound()) if not AppOwnerAuthorization().is_authorized(request, object=obj): raise ImmediateHttpResponse(response=http.HttpForbidden()) data['slug'] = data.get('slug', obj.app_slug) data.update(self.formset(data)) data.update(self.devices(data)) forms = [ AppDetailsBasicForm(data, instance=obj, request=request), DeviceTypeForm(data, addon=obj), CategoryFormSet(data, addon=obj, request=request) ] valid = all([f.is_valid() for f in forms]) if not valid: raise self.form_errors(forms) forms[0].save(obj) forms[1].save(obj) forms[2].save() log.info('App updated: %s' % obj.pk) bundle.obj = obj return bundle
def build_filters(self, filters=None): if filters is None: filters = {} orm_filters = super(VoteResource, self).build_filters( filters) # modify super(*,self) if 'parent__exact' in orm_filters: del orm_filters['parent__exact'] # delete this field since this is a GFK if 'owner__exact' in orm_filters: del orm_filters['owner__exact'] # delete this field since this is a GFK if "parent" in filters and "owner" in filters: try: parent_type = filters['parent'].split(';')[0].split('/')[2] parent_uuid_list = uuid_re.findall(filters['parent']) parent_model = ContentType.objects.get( model=parent_type).model_class() parent = parent_model.objects.filter(is_active=True, uuid__in=parent_uuid_list) user = UserProfile.objects.get( uuid=uuid_re.search(filters['owner']).group()) if not user.is_active: return orm_filters Qparent = Q(content_type__model=parent_type, object_id__in=[p.pk for p in parent]) sqs = user.vote_set.filter(Q(is_active=True), Qparent) orm_filters["pk__in"] = [i.pk for i in sqs] except Vote.DoesNotExist: orm_filters["pk__in"] = [] # return HttpGone() except Vote.MultipleObjectsReturned: orm_filters["pk__in"] = [] raise ImmediateHttpResponse(response=http.HttpNotFound()) elif "parent" in filters: # elifs: # dual filter, supports multiple parents try: obj = self.fields['parent'].build_related_resource( filters['parent']).obj if not obj.is_active: return orm_filters sqs = obj.vote_set.filter(is_active=True) orm_filters["pk__in"] = [i.pk for i in sqs] except Vote.DoesNotExist: orm_filters["pk__in"] = [] # return HttpGone() except Vote.MultipleObjectsReturned: orm_filters["pk__in"] = [] raise ImmediateHttpResponse(response=http.HttpNotFound()) return orm_filters
def obj_get(self, bundle, **kwargs): try: user = self._client.retrieve_user(kwargs['pk']) except mongodb.MongoDriver.NotFoundError: raise exceptions.ImmediateHttpResponse( response=http.HttpNotFound()) else: return user
def get_logo(self, request, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) try: party = Party.objects.get(abbreviation=kwargs.get('abbreviation')) except Party.DoesNotExist: return http.HttpNotFound() return api_get_thumbnail(request, party.logo, self.SUPPORTED_LOGO_DIMS)