def obj_update(self, bundle, **kwargs): if 'tag' not in bundle.data: raise BadRequest("tag must be specified") try: bundle.obj = FixtureDataType.get(kwargs['pk']) except ResourceNotFound: raise NotFound('Lookup table not found') if bundle.obj.domain != kwargs['domain']: raise NotFound('Lookup table not found') if bundle.obj.tag != bundle.data['tag']: raise BadRequest("Lookup table tag cannot be changed") save = False if 'is_global' in bundle.data: save = True bundle.obj.is_global = bundle.data['is_global'] if 'fields' in bundle.data: save = True bundle.obj.fields = [ FixtureTypeField.wrap(field) for field in bundle.data['fields'] ] if 'item_attributes' in bundle.data: save = True bundle.obj.item_attributes = bundle.data['item_attributes'] if save: bundle.obj.save() return bundle
def to_sdf(self, bundle_or_dict, options=None): no_struct_error_msg = 'Molecule has no structure records.' if isinstance(bundle_or_dict, dict): data_dict = bundle_or_dict if 'error_message' in data_dict and data_dict[ 'error_message'] == no_struct_error_msg: return no_struct_error_msg if 'molecules' in data_dict: ret_text = '' for molecule_bundle in data_dict['molecules']: ret_text += self.to_sdf(molecule_bundle) + '\n\n$$$$\n' return ret_text else: raise ValueError( 'Error, unexpected dictionary received with keys: {0}'. format(data_dict.keys())) elif isinstance(bundle_or_dict, Bundle): data_bundle = bundle_or_dict molecule_structures = data_bundle.data.get('molecule_structures') if not molecule_structures: raise NotFound(no_struct_error_msg) molecule_sdf = molecule_structures.data.get('molfile', None) if not molecule_sdf: raise NotFound(no_struct_error_msg) ret = molecule_sdf.rstrip() + '\n' return ret else: raise ValueError('Error, unexpected type received: {0}'.format( type(bundle_or_dict)))
def obj_update(self, bundle, **kwargs): if 'data_type_id' not in bundle.data: raise BadRequest("data_type_id must be specified") try: bundle.obj = FixtureDataItem.get(kwargs['pk']) except ResourceNotFound: raise NotFound('Lookup table item not found') if bundle.obj.domain != kwargs['domain']: raise NotFound('Lookup table item not found') save = False if 'fields' in bundle.data: save = True bundle.obj.fields = { field_name: FieldList.wrap(field_list) for field_name, field_list in bundle.data['fields'].items() } if 'item_attributes' in bundle.data: save = True bundle.obj.item_attributes = bundle.data['item_attributes'] if save: bundle.obj.save() return bundle
def obj_delete(self, request=None, **kwargs): """ A ORM-specific implementation of ``obj_delete``. Takes optional ``kwargs``, which are used to narrow the query to find the instance. """ logger.debug('CampaignDeleteCascade API get called') obj = kwargs.pop('_obj', None) if not hasattr(obj, 'delete'): try: obj = self.obj_get(request, **kwargs) except: error_msg = "A model instance matching the provided arguments could not be found." logger.error(error_msg) raise NotFound(error_msg) #obj.delete() campaign_id = obj.id try: del_campaign = Campaign.objects.get(id=campaign_id) phonebook_count = del_campaign.phonebook.all().count() if phonebook_count == 0: del_campaign.delete() else: # phonebook_count > 0 other_campaing_count =\ Campaign.objects.filter(user=request.user, phonebook__in=del_campaign.phonebook.all())\ .exclude(id=campaign_id).count() if other_campaing_count == 0: # delete phonebooks as well as contacts belong to it # 1) delete all contacts which are belong to phonebook contact_list = Contact.objects\ .filter(phonebook__in=del_campaign.phonebook.all()) contact_list.delete() # 2) delete phonebook phonebook_list = Phonebook.objects\ .filter(id__in=del_campaign.phonebook.all()) phonebook_list.delete() # 3) delete campaign del_campaign.delete() else: del_campaign.delete() logger.debug('CampaignDeleteCascade API : result ok 200') except: error_msg = "A model matching arguments not found." logger.error(error_msg) raise NotFound(error_msg)
def obj_get(self, bundle, **kwargs): """ Method copied from parent class so we can handle the case where MultipleObjectsReturned happens for Config (deletable) models. """ # Use ignore_bad_filters=True. `obj_get_list` filters based on # request.GET, but `obj_get` usually filters based on `detail_uri_name` # or data from a related field, so we don't want to raise errors if # something doesn't explicitly match a configured filter. applicable_filters = self.build_filters(filters=kwargs, ignore_bad_filters=True) if self._meta.detail_uri_name in kwargs: applicable_filters[self._meta.detail_uri_name] = kwargs[self._meta.detail_uri_name] try: object_list = self.apply_filters(bundle.request, applicable_filters) stringified_kwargs = ', '.join(["%s=%s" % (k, v) for k, v in applicable_filters.items()]) if len(object_list) <= 0: raise self._meta.object_class.DoesNotExist("Couldn't find an instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) elif len(object_list) > 1: if self._meta.queryset.model._admin.deletable is False: object_list = object_list.order_by('-id') else: raise MultipleObjectsReturned("More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) bundle.obj = object_list[0] self.authorized_read_detail(object_list, bundle) return bundle.obj except ValueError: raise NotFound("Invalid resource lookup data provided (mismatched type).")
def obj_update(self, bundle, skip_errors=False, **kwargs): """ A ORM-specific implementation of ``obj_update``. """ if not bundle.obj or not self.get_bundle_detail_data(bundle): try: lookup_kwargs = self.lookup_kwargs_with_identifiers( bundle, kwargs) except: # if there is trouble hydrating the data, fall back to just # using kwargs by itself (usually it only contains a "pk" key # and this will work fine. lookup_kwargs = kwargs try: bundle.obj = self.obj_get(bundle, **lookup_kwargs) self.post_obj_get(bundle.obj) except ObjectDoesNotExist: raise NotFound( "A model instance matching the provided arguments could not be found." ) self.authorized_update_detail(self.get_object_list(bundle.request), bundle) bundle = self.full_hydrate(bundle) self.post_full_hydrate(bundle, **kwargs) return self.save(bundle, skip_errors=skip_errors)
def obj_get(self, request=None, **kwargs): # get one object from data source pk = int(kwargs['pk']) try: return data[pk] except KeyError: raise NotFound("Object not found")
def obj_get(self, bundle, **kwargs): test_id = kwargs.get("test_id", None) test = self._read_test(test_id) if test: return test else: raise NotFound('Test with test_id %s not found' % test_id)
def obj_get(self, bundle, **kwargs): id = kwargs.get("id", None) exercise = get_exercise_data(bundle.request, id) if exercise: return Exercise(**exercise) else: raise NotFound('Exercise with id %s not found' % id)
def obj_get(self, bundle, **kwargs): event_id = int(kwargs.get('pk')) try: event = Event.objects.get(pk=event_id) except Event.DoesNotExist: raise NotFound("Organizer not found") if event.organizer: event_organizer = event.organizer match_user = MatchQuerySet.between( user_id1=bundle.request.user.id, user_id2=event_organizer.id ) if match_user: match_user = match_user[0] match_user.id = event_id else: match_user = NonMatchUser( bundle.request.user.id, event_organizer.id ) match_user.event_type = event.event_type else: fb_event = FacebookEvent.objects.filter( facebook_id=event.eid).first() obj = A() obj.id = event.id obj.first_name = fb_event.owner_info.get('name') obj.link = 'https://www.facebook.com/{}/'.format( fb_event.owner_info.get('id') ) obj.event_type = event.event_type return obj return match_user
def obj_delete(self, bundle, **kwargs): """ Adapted version of the method in TastyPie's ModelResource to take into account the c2dm_notification need """ annObj = bundle.obj if not hasattr(annObj, 'delete'): try: annObj = self.obj_get(bundle=bundle, **kwargs) except ObjectDoesNotExist: raise NotFound( "A model instance matching the provided arguments could not be found." ) receiver_profile = annObj.user registration_id = None if receiver_profile: registration_id = receiver_profile.c2dm_id params = { 'type': OrderFeature.RESOLVED_REQUEST, 'order_request': annObj.get_annotation_data() } self._make_c2dm_notification(registration_id, None, bundle, params=params) annObj.delete()
def obj_update(self, bundle, **kwargs): self._ensure_toggle_enabled(bundle.request) domain = kwargs['domain'] pk = kwargs['pk'] try: data_source = get_document_or_404(DataSourceConfiguration, domain, pk) except Http404 as e: raise NotFound(str(e)) allowed_update_fields = [ 'display_name', 'configured_filter', 'configured_indicators', ] for key, value in bundle.data.items(): if key in allowed_update_fields: data_source[key] = value try: data_source.validate() data_source.save() except BadSpecError as e: raise ImmediateHttpResponse( add_cors_headers_to_response( HttpResponse( json.dumps({ "error": _("Invalid data source! Details: {details}"). format(details=str(e)) }), content_type="application/json", status=500, ))) bundle.obj = data_source return bundle
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 obj_get(self, request=None, **kwargs): pk = int(kwargs['pk']) try: return self._new_obj( nc.get_relationship_model(nc.graphdb.manager, pk)) except KeyError: raise NotFound("Object not found")
def obj_get_no_auth_check(self, request=None, **kwargs): """ Same as the original ``obj_get`` knows when it is being called to get a nested resource. Does *not* do authorization checks. """ # TODO: merge this and original obj_get and use another argument in # kwargs to know if we should check for auth? try: object_list = self.get_object_list(request).filter(**kwargs) stringified_kwargs = ', '.join( ["%s=%s" % (k, v) for k, v in kwargs.items()]) if len(object_list) <= 0: raise self._meta.object_class.DoesNotExist( "Couldn't find an " "instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) elif len(object_list) > 1: raise MultipleObjectsReturned( "More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) return object_list[0] except ValueError: raise NotFound("Invalid resource lookup data provided (mismatched " "type).")
def obj_get(self, request=None, **kwargs): """ Same as the original ``obj_get`` but knows when it is being called to get an object from a nested resource uri. Performs authorization checks in every case. """ try: base_object_list = self.get_object_list(request).filter( **self.real_remove_api_resource_names(kwargs)) object_list = self.apply_proper_authorization_limits( request, base_object_list, **kwargs) stringified_kwargs = ', '.join( ["%s=%s" % (k, v) for k, v in kwargs.items()]) if len(object_list) <= 0: raise self._meta.object_class.DoesNotExist( "Couldn't find an " "instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) elif len(object_list) > 1: raise MultipleObjectsReturned( "More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) return object_list[0] except ValueError: raise NotFound("Invalid resource lookup data provided (mismatched " "type).")
def obj_get(self, bundle, **kwargs): assessment_item_id = kwargs.get("id", None) assessment_item = get_assessment_item_data(bundle.request, assessment_item_id) if assessment_item: return AssessmentItem(**assessment_item) else: raise NotFound('AssessmentItem with id %s not found' % assessment_item_id)
def obj_get(self, bundle, **kwargs): try: wallet = Wallet.objects.get(user=bundle.request.user) except Wallet.DoesNotExist: raise NotFound("User has no associated wallet") return wallet
def obj_get(self, bundle, **kwargs): event_id = int(kwargs.get('pk')) only_my = bundle.request.GET.get('only_my') == 'true' user_id = bundle.request.user.id attendees = Membership.objects.filter( event_id=event_id, rsvp__in=('yes', 'maybe') ).values_list('user_id', flat=True) if attendees: if only_my: my_interests = Interest.objects.filter( user_id=user_id).values_list('interest', flat=True) interest_qs = InterestSubject.objects.filter( interest__user__in=attendees, interest__interest__in=my_interests ) else: interest_qs = InterestSubject.objects.filter( interest__user__in=attendees ) interests = interest_qs.annotate( num_interests=Count('interest') ).order_by('-num_interests').values( 'description', 'num_interests', 'id' ) shared_interests = ResourseObject( { 'id': event_id, 'shared_interests': interests, 'total_count': len(interests) } ) return shared_interests else: raise NotFound("Shared interests not found")
def dispatch_classmethod(self, request, method=None, **kwargs): method_ref = self.settings.get('classmethods', {}).get(method, None) if not method_ref: raise NotFound("No such class method: %s" % method) method_callable = self._import_function(method_ref) ret = method_callable(self, request, method=method, **kwargs) return ret
def obj_get(self, **kwargs): chembl_id = kwargs.get('molecule__chembl_id') standard_inchi_key = kwargs.get('standard_inchi_key') if not chembl_id and not standard_inchi_key: raise BadRequest("ChEMBL ID or standard InChi Key required.") filters = dict((k,v) for k,v in kwargs.items() if k in ('molecule__chembl_id','standard_inchi_key')) stringified_kwargs = ', '.join(["%s=%s" % (k, v) for k, v in filters.items()]) filters.update({ 'molecule__chembl__entity_type':'COMPOUND', 'molecule__compoundstructures__isnull': False, 'molecule__compoundproperties__isnull': False, }) try: molfile_list = self.get_object_list(None).filter(**filters).values_list('molfile', flat=True) if len(molfile_list) <= 0: raise ObjectDoesNotExist("Couldn't find an instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) elif len(molfile_list) > 1: raise MultipleObjectsReturned("More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs)) except ValueError: raise NotFound("Invalid resource lookup data provided (mismatched type).") return molfile_list[0]
def put_detail(self, request, **kwargs): """Override put_detail so that it doesn't create a new resource when One doesn't exists, I don't like this reflex""" if VERSION >= (1, 4): body = request.body else: body = request.raw_post_data deserialized = self.deserialize(request, body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) try: updated_bundle = self.obj_update( bundle=bundle, **self.remove_api_resource_names(kwargs)) if not self._meta.always_return_data: return http.HttpNoContent() else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpAccepted) except (NotFound, MultipleObjectsReturned): raise NotFound( "A model instance matching the provided arguments could not be found." )
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix)-1:] try: view, args, kwargs = resolve(chomped_uri) resource_name = kwargs['resource_name'] resource_class = self.resource_mapping[resource_name] except (Resolver404, KeyError): raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri) parent_resource = resource_class(api_name=self._meta.api_name) kwargs = parent_resource.remove_api_resource_names(kwargs) return parent_resource.obj_get(**kwargs)
def obj_create(self, bundle, **kwargs): try: time_left = int(bundle.data['time_left']) except KeyError, ValueError: # missing mandatory param time_left (in seconds) # or not a int raise NotFound("No time_left argument")
def dispatch_instancemethod(self, request, method=None, **kwargs): method_ref = self.settings.get('methods', {}).get(method, None) if not method_ref: raise NotFound("No such method: %s" % method) method_callable = self._import_function(method_ref) id = kwargs.get(self._meta.detail_uri_name) if id.isdigit(): id = int(id) basic_bundle = self.build_bundle(request=request) try: obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except Exception, ex: raise NotFound("No such object %s%s/" % (self.get_list_endpoint(), id))
class PilotJobResource(ModelResource): """This resource handler jobs requests. Allowed Methods: ---------------- GET /dispatcher/{id} # Get info about an job GET /dispatcher/schema/ # Get job schema GET /dispatcher/set/{id};{id}/ # Get a list of jobs POST /dispatcher/ # Get a new job PATCH /dispatcher/{id}/ # Partially update a job """ application = fields.ToOneField(ApplicationResource, 'application', full=True) input_objs = fields.ToManyField(DataObjectResource, 'input_objs', null=True, full=True) output_objs = fields.ToManyField(DataObjectResource, 'output_objs', null=True, full=True) checkpoint_objs = fields.ToManyField(DataObjectResource, 'checkpoint_objs', null=True, full=True) class Meta: resource_name = 'dispatcher' authentication = PilotTokenAuthentication() authorization = PilotAuthorization() # Remove from query deleted jobs queryset = Job.objects.all() list_allowed_methods = ['post'] detail_allowed_methods = ['get', 'patch'] # Return data on the POST query always_return_data = True def dehydrate(self, bundle): bundle.data['slug'] = slugify(bundle.obj.name) return bundle def obj_create(self, bundle, **kwargs): try: time_left = int(bundle.data['time_left']) except KeyError, ValueError: # missing mandatory param time_left (in seconds) # or not a int raise NotFound("No time_left argument") try: bundle.obj = bundle.request.pilot.get_new_job(time_left) except StopIteration: # no jobs found raise NotFound("No jobs found") return bundle
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix) - 1:] try: view, args, kwargs = resolve(chomped_uri) except Resolver404: raise NotFound( "The URL provided '%s' was not a link to a valid resource." % uri) parent_resource = view.func_closure[0].cell_contents.func_closure[ 0].cell_contents return parent_resource.obj_get( **self.remove_api_resource_names(kwargs))
def resource_from_data(self, fk_resource, data, request=None, related_obj=None, related_name=None): """ Given a dictionary-like structure is provided, a fresh related resource is created using that data. """ # Try to hydrate the data provided. data = dict_strip_unicode_keys(data) fk_bundle = fk_resource.build_bundle(data=data, request=request) if related_obj: fk_bundle.related_obj = related_obj fk_bundle.related_name = related_name # We need to check to see if updates are allowed on the FK # resource. If not, we'll just return a populated bundle instead # of mistakenly updating something that should be read-only. if not fk_resource.can_update(): return fk_resource.full_hydrate(fk_bundle) try: return fk_resource.obj_update(fk_bundle, skip_errors=True, **data) except NotFound: try: # Attempt lookup by primary key lookup_kwargs = dict((k, v) for k, v in data.iteritems() if getattr(fk_resource, k).unique) if not lookup_kwargs: raise NotFound() return fk_resource.obj_update(fk_bundle, skip_errors=True, **lookup_kwargs) except NotFound: fk_bundle = fk_resource.full_hydrate(fk_bundle) fk_resource.is_valid(fk_bundle, request) return fk_bundle except MultipleObjectsReturned: return fk_resource.full_hydrate(fk_bundle)
def obj_get_list(self, bundle, **kwargs): application_id = bundle.request.GET.get('application_id') if not application_id: raise NotFound('application_id parameter required') domain = kwargs['domain'] couch_user = CouchUser.from_django_user(bundle.request.user) if not domain_has_privilege(domain, privileges.ZAPIER_INTEGRATION ) or not couch_user.is_member_of(domain): raise ImmediateHttpResponse( HttpForbidden( 'You are not allowed to get list of forms for this domain') ) results = [] application = Application.get(docid=application_id) if not application: return [] forms_objects = application.get_forms(bare=False) for form_object in forms_objects: form = form_object['form'] module = form_object['module'] form_name = '{} > {} > {}'.format(application.name, module.default_name(), form.default_name()) results.append(Form(form_xmlns=form.xmlns, form_name=form_name)) return results
def obj_get(self, request=None, **kwargs): # get one object from data source pk = int(kwargs['pk']) try: return consul_session.kv[self._meta.consul_key_root + pk] except AttributeError: raise NotFound("Object not found")