class EmployeeAssignmentResource(ModelResource): employee = fields.ForeignKey(EmployeeResource, attribute="employee") assignment = fields.ForeignKey(AssignmentResource, attribute="assignment") class Meta: always_return_data = True queryset = EmployeeAssignment.objects.all() resource_name = "employee_assignment" include_resource_uri = False fields = ("id", "hours", "overtime") filtering = { "employee": ('exact', ), "assignment": ALL_WITH_RELATIONS, } allowed_methods = ['get', 'put', 'post', 'delete'] authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() def hydrate(self, bundle): bundle = super(EmployeeAssignmentResource, self).hydrate(bundle) if not bundle.data.get('is_confirmed', False): bundle.obj.check_in = bundle.obj.check_out = None else: assignment = Assignment.objects.get(id=bundle.obj.assignment_id) bundle.obj.check_in = assignment.start_datetime bundle.obj.check_out = assignment.end_datetime return bundle
class EnrichmentNoteResource(ModelResource): """Enrichment Note Resource.""" species = fields.ForeignKey('paws.api.resources.SpeciesResource', 'species', full=True) enrichment = fields.ForeignKey('paws.api.resources.EnrichmentResource', 'enrichment', full=True) class Meta: authentication = CustomAuthentication() authorization = DjangoAuthorization() queryset = models.EnrichmentNote.objects.all() resource_name = 'enrichmentNote' list_allowed_methods = ['get', 'post', 'put', 'delete'] # Redefine get_object_list to filter for enrichment_id and species_id. def get_object_list(self, request): species_id = request.GET.get('species_id', None) enrichment_id = request.GET.get('enrichment_id', None) q_set = super(EnrichmentNoteResource, self).get_object_list(request) # Could filter by multiple species: split species_id by comma species_id_list = [] if species_id != None: for s in species_id.split(','): if s != '': species_id_list.append(int(s)) # Try filtering by species first. if species_id != None: try: species_list = models.Species.objects.filter( id__in=species_id_list) q_set = q_set.filter(species__in=species_list) except ObjectDoesNotExist: pass # Try filtering by enrichment next. try: enrichment = models.Enrichment.objects.get(id=enrichment_id) q_set = q_set.filter(enrichment=enrichment) return q_set except ObjectDoesNotExist: pass return q_set
class BehaviorResource(ModelResource): """Behavior Resource.""" enrichment = fields.ForeignKey('paws.api.resources.EnrichmentResource', 'enrichment') class Meta: authentication = CustomAuthentication() authorization = Authorization() queryset = models.Behavior.objects.all() resource_name = 'behavior' list_allowed_methods = ['get', 'post', 'put', 'delete'] always_return_data = True # Redefine get_object_list to filter for enrichment_id def get_object_list(self, request): enrichment_id = request.GET.get('enrichment_id', None) q_set = super(BehaviorResource, self).get_object_list(request) # Try filtering by enrichment if it exists. try: enrichment = models.Enrichment.objects.get(id=enrichment_id) q_set = q_set.filter(enrichment=enrichment) except ObjectDoesNotExist: pass return q_set
class NotificationResource(ModelResource): datastore_owner = fields.ForeignKey(ProfileResource, "datastore_owner", full=True) def obj_create(self, bundle, request=None, **kwargs): bundle = super(NotificationResource, self).obj_create(bundle, request, **kwargs) profile = Profile.objects.get( uuid=bundle.data["datastore_owner"]["uuid"]) devices = Device.objects.filter(datastore_owner=profile) if devices.count() > 0: gcm = GCM(settings.ASSISTANT_GCM_API_KEY) for device in devices: try: gcm.plaintext_request(registration_id=device.gcm_reg_id, data={"action": "notify"}) except Exception as e: print e return bundle class Meta: queryset = Notification.objects.all() allowed_methods = ("get", "post", "delete") authentication = OAuth2Authentication("funf_write") authorization = PDSAuthorization(scope="funf_write", audit_enabled=True) filtering = {"datastore_owner": ALL_WITH_RELATIONS} ordering = ("timestamp") limit = 20
class DayOffResource(ModelResource): employee = fields.ForeignKey(EmployeeResource, attribute="employee", full=True) class Meta: always_return_data = True queryset = DayOff.objects.all() resource_name = "dayoff" include_resource_uri = False fields = ( "id", "start_datetime", "end_datetime", ) filtering = { "employee": ('exact', ), "start_datetime": ALL, } allowed_methods = ['get', 'post', 'put', 'delete'] authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() def dehydrate(self, bundle, *args, **kwargs): bundle = super(DayOffResource, self).dehydrate(bundle) dayoff = bundle.obj bundle.data["start_date"] = dayoff.start_datetime.date() bundle.data["start_time"] = dayoff.start_datetime.time() bundle.data["end_date"] = dayoff.end_datetime.date() bundle.data["end_time"] = dayoff.end_datetime.time() return bundle
class AdminPhotoResource(MultipartResource, ModelResource): album = fields.ForeignKey(AdminAlbumResource, 'album', full=True, null=True, blank=True) class Meta: queryset = Photo.objects.all() resource_name = 'admin_photos' list_allowed_methods = ['get', 'post'] detailed_allowed_methods = ['get', 'post', 'put', 'delete', 'patch'] authentication = MultiAuthentication(BasicAuthentication(), ApiKeyAuthentication()) authorization = DjangoAuthorization() filtering = {'album': ALL_WITH_RELATIONS} def dehydrate_img(self, bundle): if bundle.obj.img: bundle.data['img'] = { 'original': bundle.obj.img.url, 'small': bundle.obj.img['small'].url, 'medium': bundle.obj.img['medium'].url, 'large': bundle.obj.img['large'].url, 'xl': bundle.obj.img['xl'].url, 'xxl': bundle.obj.img['xxl'].url } return bundle.data['img']
class EntryResource(ModelResource): user = fields.ForeignKey(to=UserResource, attribute='user', full=True, null=True) class Meta: resource_name = "entries" queryset = Entry.objects.all() include_resource_uri = False limit = 10 fields = ['created', 'slug', 'title', 'user', 'image'] # paginator_class = Paginator authorization = Authorization() # authentication = Authentication() # 默认 OnlyRead post不被允许 authentication = BasicAuthentication() # tests中使用 # authentication = SessionAuthentication() # runserver 时使用 def prepend_urls(self): return [ re_path(r"(?P<resource_name>%s)/test_custom_api%s$" % (self._meta.resource_name, trailing_slash), self.wrap_view('test_custom_api'), name="api_custom_api"), re_path(r"(?P<resource_name>%s)/test_custom_api2%s$" % (self._meta.resource_name, trailing_slash), self.wrap_view('test_custom_api2'), name="api_custom_api2"), re_path(r"(?P<resource_name>%s)/test_custom_api3%s$" % (self._meta.resource_name, trailing_slash), self.wrap_view('test_custom_api3'), name="api_custom_api3"), re_path(r"(?P<resource_name>%s)/test_custom_api4%s$" % (self._meta.resource_name, trailing_slash), self.wrap_view('test_custom_api4'), name="api_custom_api4"), ] @custom_api(allowed=["get"], login_required=True) def test_custom_api(self, request, **kwargs): data = {"api": "api"} return Result(data=data) @custom_api(allowed=["get"], login_required=False) def test_custom_api2(self, request, **kwargs): data = {"api2": "api2"} return Result(data=data) @custom_api(allowed=["get", "post"], login_required=False) def test_custom_api3(self, request, **kwargs): data = {"apia": "apia"} return Result(data=data) def test_custom_api4(self, request, **kwargs): data = {"apia": "apia"} return Result(data=data) def get_list(self, request, **kwargs): return super(EntryResource, self).get_list(request, **kwargs)
class PersonalAccountBalanceResource(OthersAccountBalanceResource): employee = fields.ForeignKey(EmployeeResource, attribute="employee", related_name="my_balance") class Meta: queryset = PersonalAccountBalance.objects.all() resource_name = "personal_account_balance" fields = ("id", "date",) allowed_methods = ['get',]
class AssignmentResource(BasicAssignmentResource): project = fields.ForeignKey(ProjectResource, attribute="project", full=True, readonly=True) class Meta(BasicAssignmentResource.Meta): always_return_data = True include_resource_uri = False queryset = Assignment.objects.all() resource_name = "assignment" fields = ("id", "comment", "start_datetime", "end_datetime", "number_needed") allowed_methods = ['get', 'post', 'put'] authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() filtering = { "project": ("exact", ), "start_datetime": ALL, "is_insuranced": "exact", } def employee_list(self, assignment): """ list of all employees """ availables = Employee.objects.exclude( Q(assignments__end_datetime__range=assignment.time_range) | Q(assignments__start_datetime__range=assignment.time_range), ~Q(assignments=assignment), ).distinct() return [{ 'id': employee.id, 'contact': { 'name': employee.contact.name } } for employee in availables] def dehydrate(self, bundle, *args, **kwargs): bundle = super(AssignmentResource, self).dehydrate(bundle) assignment = bundle.obj bundle.data["start_date"] = assignment.start_datetime.date() bundle.data["start_time"] = assignment.start_datetime.time() bundle.data["end_date"] = assignment.end_datetime.date() bundle.data["end_time"] = assignment.end_datetime.time() bundle.data["availables"] = self.employee_list(assignment) return bundle def build_filters(self, filters=None, **kwargs): orm_filters = super(AssignmentResource, self).build_filters(filters, **kwargs) if 'selected_datetime' in filters: date = dateparse.parse_date(filters['selected_datetime']) orm_filters['start_datetime__gte'] = date orm_filters['start_datetime__lt'] = date + datetime.timedelta( days=1) return orm_filters
class BookResource(ModelResource): class Meta: queryset = Book.objects.all() resource_name = 'book' publisher = fields.ForeignKey(PublisherResource, 'publisher') def determine_format(self, request): return 'application/json'
class SalaryResource(ModelResource): employee = fields.ForeignKey(EmployeeResource, attribute="employee", related_name="salaries") class Meta: queryset = PersonalWithdraw.objects.all() resource_name = "personal_withdraw" fields = ("id", "hourly", "overtime", "start_time") allowed_methods = ['get','post','put'] authentication = ApiKeyAuthentication() authorization = DjangoAuthorization()
class TemplateResource(ModelResource): plugin = fields.ForeignKey('plugin.api.PluginResource', 'plugin') sequence = fields.ManyToManyField('template.api.TemplateResource', 'sequence') class Meta: queryset = Template.objects.all() authentication = SessionAuthentication() authorization = UserObjectsOnlyAuthorization() serializer = CamelCaseJSONSerializer() filtering = {'is_root': ('exact', )}
class ScopeResource(ModelResource): datastore_owner = fields.ForeignKey(ProfileResource, "datastore_owner", full=True, blank=False) class Meta: resource_name = 'scope' queryset = Scope.objects.all() authentication = OAuth2Authentication("funf_write") authorization = PDSAuthorization(scope="funf_write", audit_enabled=True) filtering = {"datastore_owner": ALL_WITH_RELATIONS}
class SubCategoryResource(ModelResource): parent = fields.ForeignKey('self', 'parent', null=True, blank=True, full=True) class Meta: queryset = Category.objects.all() resource_name = 'subcategory' allowed_methods = ['get'] filtering = { 'parent': ['isnull', 'exact'], }
class RoleResource(ModelResource): datastore_owner = fields.ForeignKey(ProfileResource, "datastore_owner", full=True, blank=False) class Meta: resource_name = 'role' queryset = Role.objects.all() list_allowed_methods = ["delete", "get", "post"] authentication = OAuth2Authentication("funf_write") authorization = PDSAuthorization(scope="funf_write", audit_enabled=True) filtering = {"datastore_owner": ALL_WITH_RELATIONS}
class AuditEntryResource(ModelResource): datastore_owner = fields.ForeignKey(ProfileResource, 'datastore_owner', full=True) requester = fields.ForeignKey(ProfileResource, 'requester', full=True) def dehydrate(self, bundle): # Sending this over the line is a waste of bandwidth... # When we have the time, we should make this formatting happen on the client side from the raw timestamp bundle.data['timestamp_date'] = bundle.data['timestamp'].date() bundle.data['timestamp_time'] = bundle.data['timestamp'].time( ).strftime('%I:%M:%S %p') return bundle #def dispatch(self, request_type, request, **kwargs): # # This method is used for pulling the datastore_owner out of the url path, rather than a querystring parameter # # This is not supported in v0.3 # pdb.set_trace() # owner_uuid = kwargs.pop("owner_uuid") # kwargs["datastore_owner"], created = Profile.objects.get_or_create(uuid = owner_uuid) # return super(AuditEntryResource, self).dispatch(request_type, request, **kwargs) class Meta: queryset = AuditEntry.objects.all() # POST is provided to allow a Resource or Sandbox server to store audit entries on the PDS allowed_methods = ('get', 'post') authentication = OAuth2Authentication("funf_write") authorization = PDSAuthorization(scope="funf_write", audit_enabled=False) filtering = { "datastore_owner": ALL_WITH_RELATIONS, "timestamp": ["gte", "lte", "gt", "lt"], "script": ["contains"], "requester": ALL_WITH_RELATIONS } ordering = ('timestamp') limit = 20
class AdminCreditResource(ModelResource): post = fields.ForeignKey(AdminPostResource, 'post', full=True, null=True, blank=True) class Meta: queryset = Credit.objects.all() resource_name = 'admin_credits' list_allowed_methods = ['get', 'post'] detailed_allowed_methods = ['get', 'post', 'put', 'delete'] authentication = MultiAuthentication(BasicAuthentication(), ApiKeyAuthentication()) authorization = DjangoAuthorization()
class ExtraAdminCategoryResource(ModelResource): parent = fields.ForeignKey('self', 'parent', null=True, blank=True, full=True) class Meta: queryset = Category.objects.all() resource_name = 'admin_categories' list_allowed_methods = ['get', 'post'] detailed_allowed_methods = ['get', 'post', 'put', 'delete'] authentication = MultiAuthentication(BasicAuthentication(), ApiKeyAuthentication()) authorization = DjangoAuthorization()
class Entry2Resource(ModelResource): user = fields.ForeignKey(to=UserResource, attribute='user', full=True, null=True) class Meta: resource_name = "entries2" queryset = Entry.objects.all() include_resource_uri = False fields = ['created', 'slug', 'title', 'user', 'image'] # paginator_class = Paginator authorization = Authorization() # authentication = Authentication() # 默认 OnlyRead post不被允许 # authentication = BasicAuthentication() # tests中使用 authentication = SessionAuthentication() # runserver 时使用
class QuoteResource(ModelResource): poster = fields.ForeignKey(UserResource, 'poster') class Meta: queryset = models.Quote.objects.all() allowed_methods = ['get', 'post'] always_return_data = True authorization = Authorization() def obj_create(self, bundle, **kwargs): if bundle.request.user.is_authenticated(): return super(QuoteResource, self).obj_create(bundle, poster=bundle.request.user, **kwargs) raise ImmediateHttpResponse(HttpUnauthorized('Not authenticated'))
class PostResource(ModelResource): category = fields.ForeignKey(SubCategoryResource, 'category', full=True, null=True, blank=True) credits = fields.ToManyField( CreditResource, lambda bundle: bundle.obj.credits.order_by('id'), full=True, use_in='detail', null=True, blank=True) tags = fields.ToManyField(TagResource, lambda bundle: bundle.obj.tags.all(), use_in='detail', full=True, null=True, blank=True) images = fields.ToManyField( ImageResource, lambda bundle: bundle.obj.images.order_by('-is_cover', 'id'), full=True, use_in='detail', null=True, blank=True) cover = fields.ToOneField(ImageResource, lambda bundle: Image.objects.filter( post=bundle.obj, is_cover=True).first(), use_in='list', full=True, null=True) class Meta: queryset = Post.objects.order_by('-id') resource_name = 'posts' list_allowed_methods = [ 'get', ] detailed_allowed_methods = [ 'get', ] filtering = { 'category': ALL_WITH_RELATIONS, 'published': ['exact'], 'starred': ['exact'] }
class SectionResouce(ModelResource): content = fields.ForeignKey(ContentResouce, 'content', full=True) class Meta: queryset = Section.objects.all() resource_name = 'section' filtering = { 'subtitle_fa': ALL, 'subtitle_ar': ALL, 'body_fa': ALL, 'body_ar': ALL, 'description_fa': ALL, 'description_ar': ALL, 'content': ALL_WITH_RELATIONS, } allowed_methods = ['get', 'post'] include_resource_uri = False
class IncidentResource(ReadOnlyFieldNamespacedModelResource): status = fields.ForeignKey(StatusResource, 'status', full=True, null=True, blank=True) #TODO: We need to include the related user object at some point def hydrate(self, bundle): u = User.objects.get(username=bundle.request.GET['username']) bundle.obj.user = u return bundle class Meta: readonly_fields = ['created', 'updated'] queryset = Incident.objects.all() allowed_methods = ['get', 'post', 'delete'] resource_name = 'incident' authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True filtering = { 'created': ALL, 'updates': ALL, 'status': ALL_WITH_RELATIONS, }
class DeviceResource(ModelResource): datastore_owner = fields.ForeignKey(ProfileResource, "datastore_owner", full=True) def obj_create(self, bundle, request=None, **kwargs): #pdb.set_trace() profile = Profile.objects.get( uuid=bundle.data["datastore_owner"]["uuid"]) devices = Device.objects.filter(datastore_owner=profile) if devices.count() > 0: # Note: we're trying to keep only the most recent... not the best way to do it, but it works devices.delete() return super(DeviceResource, self).obj_create(bundle, request, **kwargs) class Meta: queryset = Device.objects.all() allowed_methods = ("get", "post", "delete") authentication = OAuth2Authentication("funf_write") authorization = PDSAuthorization(scope="funf_write", audit_enabled=True) filtering = {"datastore_owner": ALL_WITH_RELATIONS} limit = 20
class SubcategoryResource(ModelResource): """Subcategory Resource.""" category = fields.ForeignKey('paws.api.resources.CategoryResource', 'category', full=True) class Meta: authentication = CustomAuthentication() authorization = DjangoAuthorization() queryset = models.Subcategory.objects.all() resource_name = 'subcategory' list_allowed_methods = ['get', 'post', 'put', 'delete'] # Redefine get_object_list to filter for category_id. def get_object_list(self, request): category_id = request.GET.get('category_id', None) q_set = super(SubcategoryResource, self).get_object_list(request) try: category = models.Category.objects.get(id=category_id) q_set = q_set.filter(category=category) except ObjectDoesNotExist: pass return q_set
class SplitTransactionResource(ModelResource): total_value = fields.DecimalField(attribute='total_value', default=Decimal(0)) installments = fields.IntegerField(attribute='installments') first_installment_date = fields.DateField() category = fields.ForeignKey(CategoryResource, 'category', full=True, null=True) description = fields.CharField(attribute='description', null=True, blank=True) transactions = fields.ToManyField( TransactionResource, attribute=lambda bundle: Transaction.objects.filter( installment_of=bundle.obj).order_by('installment_number'), full=True, null=True) class Meta: resource_name = "split_transaction" queryset = SplitTransaction.objects.all()\ .annotate(total_value=Sum('transactions__value'))\ .annotate(installments=Count('transactions')) always_return_data = True authentication = MultiAuthentication(SessionAuthentication(), BasicAuthentication()) authorization = UserObjectsOnlyAuthorization() validation = CleanedDataFormValidation( form_class=SplitTransactionApiForm) list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get'] def _create_installments(self, bundle): """ Creates the installments for this split transaction. """ data = bundle.data transaction_data = { 'value': data.get('total_value') / data.get('installments'), 'date': data.get('first_installment_date'), 'user': bundle.obj.user, 'description': data.get('description'), 'created': timezone.now(), 'category': bundle.obj.category } transactions = [] for i in range(0, data['installments']): transactions.append( Transaction.objects.create(installment_number=(i + 1), **transaction_data)) transaction_data['date'] += relativedelta(months=1) return transactions def hydrate_total_value(self, bundle): value = bundle.data.get('total_value', None) if value: bundle.data['total_value'] = parse_decimal( str(value), locale=bundle.request.locale) return bundle def full_hydrate(self, bundle): bundle = super(SplitTransactionResource, self).full_hydrate(bundle) # this must happen after all hydrations because order isn't garanteed value = bundle.data.get('total_value') if value: # casting value to str to avoid repeating decimals value = Decimal(str(value)).copy_abs() if bundle.obj.category.is_negative: value = value.copy_negate() bundle.data['total_value'] = value return bundle def alter_detail_data_to_serialize(self, request, bundle): data = bundle.data del data['category'] del data['first_installment_date'] return bundle def alter_list_data_to_serialize(self, request, data): for bundle in data['objects']: del bundle.data['category'] del bundle.data['first_installment_date'] return data def obj_create(self, bundle, **kwargs): bundle = super(SplitTransactionResource, self).obj_create(bundle, user=bundle.request.user, **kwargs) bundle.obj.transactions = self._create_installments(bundle) return bundle
class AnimalObservationResource(ModelResource): """AnimalObservation Resource.""" animal = fields.ToOneField('paws.api.resources.AnimalResource', 'animal', full=True, related_name='animal_observations') observation = fields.ToOneField('paws.api.resources.ObservationResource', 'observation', related_name='animal_observations') behavior = fields.ForeignKey('paws.api.resources.BehaviorResource', 'behavior', full=True, null=True, blank=True) class Meta: authentication = CustomAuthentication() authorization = Authorization() queryset = models.AnimalObservation.objects.all() resource_name = 'animalObservation' list_allowed_methods = ['get', 'post', 'put', 'patch', 'delete'] # A check to see if staff can modify this observation. def can_modify_observation(self, request, animalObservation_id): # Any superuser can modify an observation. if (request.user.is_superuser): return True try: observation = models.AnimalObservation.objects.get( id=animalObservation_id).observation return observation.staff.user == request.user except ObjectDoesNotExist: return True def obj_create(self, bundle, request=None, **kwargs): # Get the user of the observation by fully hydrating the bundle and then # check if the user is allowed to add to this observation. user = self.full_hydrate(bundle).obj.observation.staff.user if not request.user.is_superuser and user != request.user: raise ImmediateHttpResponse( HttpUnauthorized( "Cannot add other users' animal observations")) return super(AnimalObservationResource, self).obj_create(bundle, request, **kwargs) def obj_update(self, bundle, request=None, **kwargs): # PATCH fix bundle.data['animal'] = bundle.data['animal'].data['resource_uri'] if not isinstance(bundle.data['behavior'], basestring): bundle.data['behavior'] = bundle.data['behavior'].data[ 'resource_uri'] # Make sure that the user can modifty. ao_id = int(kwargs.pop('pk', None)) if not self.can_modify_observation(request, ao_id): raise ImmediateHttpResponse( HttpUnauthorized( "Cannot edit other users' animal observations")) return super(AnimalObservationResource, self).obj_update(bundle, request, **kwargs) def obj_delete(self, request=None, **kwargs): # Make sure that the user can modifty. observation_id = int(kwargs.pop('pk', None)) if not self.can_modify_observation(request, observation_id): raise ImmediateHttpResponse( HttpUnauthorized( "Cannot delete other users' animal observations")) return super(AnimalObservationResource, self).obj_delete(request, **kwargs) # Redefine get_object_list to filter for observation_id and animal_id. def get_object_list(self, request): animal_id = request.GET.get('animal_id', None) observation_id = request.GET.get('observation_id', None) q_set = super(AnimalObservationResource, self).get_object_list(request) # Try filtering by animal if it exists. try: animal = models.Animal.objects.get(id=animal_id) q_set = q_set.filter(animal=animal) except ObjectDoesNotExist: pass # Try filtering by observation if it exists. try: observation = models.Observation.objects.get(id=observation_id) q_set = q_set.filter(observation=observation) except ObjectDoesNotExist: pass return q_set # Add useful numerical numbers for animal observation def dehydrate(self, bundle): # If there is no observation, set the rate equals to 0 rate = 0 if bundle.obj.interaction_time is not None and bundle.obj.observation_time is not None and bundle.obj.indirect_use is False and bundle.obj.observation_time != 0: # Add the rate of the interaction vs. total observation time # The rate = interaction time is divided by the total observation time rate = bundle.obj.interaction_time / float( bundle.obj.observation_time) # Add the rate into the API results bundle.data['rate'] = rate return bundle # override the url for a specific url path of searching def override_urls(self): return [ url(r"^(?P<resource_name>%s)\.(?P<format>\w+)/stats%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_stats'), name="api_get_stats"), ] # determine the format of the returning results in json or xml def determine_format(self, request): if (hasattr(request, 'format') and request.format in self._meta.serializer.formats): return self._meta.serializer.get_mime_for_format(request.format) return super(AnimalObservationResource, self).determine_format(request) # wraps the method 'get_seach' so that it can be called in a more functional way def wrap_view(self, view): def wrapper(request, *args, **kwargs): request.format = kwargs.pop('format', None) wrapped_view = super(AnimalObservationResource, self).wrap_view(view) return wrapped_view(request, *args, **kwargs) return wrapper # Calculate interaction rate between one given enrichment with other given enrichments def get_stats(self, request, **kwargs): # get the animal_id from url animal_id = request.GET.get('animal_id', None) animal = models.Animal.objects.get(id=animal_id) q_set = self.get_object_list(request) # filter by animal_id if exists try: q_set.filter(animal=animal) except ObjectDoesNotExist: pass # list of different enrichment given to animal with id=animal_id enrichment_list = [] total_interaction = 0.0 for result in q_set: # updating the interaction time total_interaction += result.interaction_time observation = models.Observation.objects.get( id=result.observation_id) # Make unique enrichment list if observation.enrichment in enrichment_list: pass else: enrichment_list.append(observation.enrichment) percent = [] # calculate the percentage of each enrichment's interaction time # over the total interaction time of animal with id=animal_id for e in enrichment_list: total_eachInteraction = 0.0 # behavior occurance positive = 0 NA = 0 negative = 0 avoid = 0 # total time of each occurance pos_interaction = 0.0 na_interaction = 0.0 neg_interaction = 0.0 avoid_interaction = 0.0 for result in q_set: if models.Observation.objects.get( id=result.observation_id).enrichment == e: behavior = models.Behavior.objects.get( id=result.behavior_id) total_eachInteraction += result.interaction_time if (behavior.reaction == 1): positive += 1 pos_interaction += result.interaction_time if (behavior.reaction == 0): NA += 1 na_interaction += result.interaction_time if (behavior.reaction == -1): negative += 1 neg_interaction += result.interaction_time if (behavior.reaction == -2): avoid += 1 avoid_interaction += result.interaction_time else: pass # Return 0 if the animal has never interacted with any enrichment if total_eachInteraction == 0.0: percentage = 0.0 pos_percentage = 0.0 na_percentage = 0.0 neg_percentage = 0.0 avoid_percentage = 0.0 else: percentage = total_eachInteraction / total_interaction pos_percentage = pos_interaction / total_eachInteraction na_percentage = na_interaction / total_eachInteraction neg_percentage = neg_interaction / total_eachInteraction avoid_percentage = avoid_interaction / total_eachInteraction # create bundle that stores the result object bundle = self.build_bundle(obj=e, request=request) # reformating the bundle # adding the enrichment name into the bundle bundle.data['Enrichment'] = e bundle.data['id'] = e.id # adding the percentage into the bundle bundle.data['overall_percentage'] = percentage bundle.data['positive_occurance'] = positive bundle.data['positive_percentage'] = pos_percentage bundle.data['na_occurance'] = NA bundle.data['na_percentage'] = na_percentage bundle.data['negative_interaction'] = negative bundle.data['neg_occurance'] = neg_percentage bundle.data['avoid_occuranve'] = avoid bundle.data['avoid_percentage'] = avoid_percentage # append the bundle into the list percent.append(bundle) # Specifiy the format of json output object_list = { 'objects': percent, } # Return the search results in json format return self.create_response(request, object_list)
class EnrichmentResource(ModelResource): """Enrichment Resource.""" subcategory = fields.ForeignKey('paws.api.resources.SubcategoryResource', 'subcategory', full=True) class Meta: authentication = CustomAuthentication() authorization = DjangoAuthorization() queryset = models.Enrichment.objects.all() resource_name = 'enrichment' list_allowed_methods = ['get', 'post', 'put', 'delete'] # override the url for a specific url path of searching def override_urls(self): return [ url(r"^(?P<resource_name>%s)\.(?P<format>\w+)/search%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_search'), name="api_get_search"), url(r"^(?P<resource_name>%s)/bulk%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('bulk_add'), name="api_bulk_add"), ] # determine the format of the returning results in json or xml def determine_format(self, request): if (hasattr(request, 'format') and request.format in self._meta.serializer.formats): return self._meta.serializer.get_mime_for_format(request.format) return super(EnrichmentResource, self).determine_format(request) # wraps the method 'get_seach' so that it can be called in a more functional way def wrap_view(self, view): def wrapper(request, *args, **kwargs): request.format = kwargs.pop('format', None) wrapped_view = super(EnrichmentResource, self).wrap_view(view) return wrapped_view(request, *args, **kwargs) return wrapper # main function for searching def get_search(self, request, **kwargs): # checking user inputs' method self.method_check(request, allowed=['get']) # checking if the user is authenticated self.is_authenticated(request) # checking if the user should be throttled self.throttle_check(request) # Provide the results for a search query sqs = SearchQuerySet().models(models.Enrichment).load_all().auto_query( request.GET.get('q', '')) paginator = Paginator(sqs, 20) try: page = paginator.page(int(request.GET.get('page', 1))) except InvalidPage: raise Http404("Sorry, no results on that page.") # Create a list of objects that contains the search results objects = [] for result in page.object_list: # create bundle that stores the result object bundle = self.build_bundle(obj=result.object, request=request) # reformating the bundle bundle = self.full_dehydrate(bundle) # adding the bundle into a list of objects objects.append(bundle) # Specifiy the format of json output object_list = { 'objects': objects, } # Handle the recording of the user's access for throttling purposes. self.log_throttled_access(request) # Return the search results in json format return self.create_response(request, object_list) # Redefine get_object_list to filter for subcategory_id. def get_object_list(self, request): subcategory_id = request.GET.get('subcategory_id', None) q_set = super(EnrichmentResource, self).get_object_list(request) # Try filtering by subcategory if it exists. try: subcategory = models.Subcategory.objects.get(id=subcategory_id) q_set = q_set.filter(subcategory=subcategory) except ObjectDoesNotExist: pass return q_set # Bulk add view. def bulk_add(self, request, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) # Make sure user is superuser. if not request.user.is_superuser: raise ImmediateHttpResponse(HttpUnauthorized("Cannot bulk add")) # try loading the json try: enrichment_list = json.loads(request.raw_post_data) except ValueError, e: raise ValueError('Bad JSON: %s' % e) print enrichment_list # importing the new enrichment into the database import_enrichment = bulk_import.importEnrichments(enrichment_list) # build new enrichments bundles objects = [] for result in import_enrichment: # create bundle that stores the result object bundle = self.build_bundle(obj=result, request=request) # reformating the bundle bundle = self.full_dehydrate(bundle) # adding the bundle into a list of objects objects.append(bundle) # Specifiy the format of json output object_list = { 'objects': objects, } return self.create_response(request, object_list)
class ObservationResource(ModelResource): """Observation Resource.""" animal_observations = fields.ToManyField( 'paws.api.resources.AnimalObservationResource', 'animalobservation_set', full=True, null=True, related_name='observation') enrichment = fields.ForeignKey('paws.api.resources.EnrichmentResource', 'enrichment', full=True) staff = fields.ForeignKey('paws.api.resources.StaffResource', 'staff') class Meta: authentication = CustomAuthentication() authorization = Authorization() queryset = models.Observation.objects.all() resource_name = 'observation' list_allowed_methods = ['get', 'post', 'put', 'delete'] # A check to see if staff can modify this observation. def can_modify_observation(self, request, observation_id): # Any superuser can modify an observation. if (request.user.is_superuser): return True try: observation = models.Observation.objects.get(id=observation_id) return observation.staff.user == request.user except ObjectDoesNotExist: return True # creating new observation into database def obj_create(self, bundle, request=None, **kwargs): return super(ObservationResource, self).obj_create(bundle, request, **kwargs) # update observation's information in the database def obj_update(self, bundle, request=None, **kwargs): # Clean related fields into URI's instead of bundles # PATCH fix bundle.data['enrichment'] = bundle.data['enrichment'].data[ 'resource_uri'] for key, animalObservation in enumerate( bundle.data['animal_observations']): bundle.data['animal_observations'][key] = animalObservation.data[ 'resource_uri'] # Make sure that the user can modifty. observation_id = int(kwargs.pop('pk', None)) if not self.can_modify_observation(request, observation_id): raise ImmediateHttpResponse( HttpUnauthorized("Cannot edit other users' observations")) return super(ObservationResource, self).obj_update(bundle, request, **kwargs) # delete observation from the database def obj_delete(self, request=None, **kwargs): # Make sure that the user can modifty. observation_id = int(kwargs.pop('pk', None)) if not self.can_modify_observation(request, observation_id): raise ImmediateHttpResponse( HttpUnauthorized("Cannot edit other users' observations")) return super(ObservationResource, self).obj_delete(request, **kwargs) # Redefine get_object_list to filter for enrichment_id and staff_id. def get_object_list(self, request): show_completed = request.GET.get('show_completed', None) staff_id = request.GET.get('staff_id', None) enrichment_id = request.GET.get('enrichment_id', None) q_set = super(ObservationResource, self).get_object_list(request) # Filter completed observations if not show_completed: q_set = q_set.filter(date_finished__isnull=True) # Try filtering by staff_id if it exists. try: staff = models.Staff.objects.get(id=staff_id) q_set = q_set.filter(staff=staff) except ObjectDoesNotExist: pass # Try filtering by enrichment if it exists. try: enrichment = models.Enrichment.objects.get(id=enrichment_id) q_set = q_set.filter(enrichment=enrichment) except ObjectDoesNotExist: pass return q_set
class OthersAccountBalanceResource(AbstractAccountBalanceResource): master = fields.ForeignKey(AccountBalanceResource, attribute="master", related_name="others_account_balance") class Meta: # queryset = OthersAccountBalance.objects.all() #AttributeError: type object 'OthersAccountBalance' has no attribute 'objects' resource_name = "others_account_balance"