class SBIResource(SimpleResource): text = fields.CharField(readonly=True, attribute='text') valid = fields.DateTimeField(readonly=True, attribute='valid', null=True) expires = fields.DateField(readonly=True, attribute='expires', null=True) accepted = fields.DateField(readonly=True, attribute='accepted', null=True) class Meta(SimpleResource.Meta): resource_name = 'sbi' allowed_methods = ['get'] list_allowed_methods = ['post'] def obj_create(self, bundle, request, **kwargs): form = SBIForm(bundle.data) if not form.is_valid(): raise self.form_errors(form) try: res = self.client('AcceptSBIAgreement', form.bango_data, raise_on=(SBI_ALREADY_ACCEPTED)) except BangoFormError, exc: if exc.id != SBI_ALREADY_ACCEPTED: raise res = self.client('GetAcceptedSBIAgreement', form.bango_data) seller_bango = form.cleaned_data['seller_bango'] seller_bango.sbi_expires = res.sbiAgreementExpires seller_bango.save() bundle.obj = SBIAgreement('', None, res.acceptedSBIAgreement, res.sbiAgreementExpires) return bundle
class JobCountResource(StatisticsResource): """ Number of jobs for each backend in a given time period """ start_date = fields.DateField(attribute="start_date") end_date = fields.DateField(attribute="end_date") counts = fields.DictField(attribute="counts") class Meta: resource_name = "statistics/job-count" list_allowed_methods = ['get'] detail_allowed_methods = [] def get_object_list(self, request): if "start" in request.GET: period_start = datetime(*map(int, request.GET["start"].split("-")), tzinfo=pytz.UTC) period_end = datetime(*map(int, request.GET["end"].split("-")), tzinfo=pytz.UTC) else: today = date.today() period_end = datetime(today.year, today.month, today.day, tzinfo=pytz.UTC) period_start = period_end - timedelta(30) interval = int(request.GET.get("interval", 7)) assert isinstance(period_start, datetime) assert isinstance(period_end, datetime) assert isinstance(interval, int) results = [] counts = defaultdict(lambda: 0) for platform in STANDARD_QUEUES: jobs = Job.objects.filter( status__in=('finished', 'error'), hardware_platform=platform, timestamp_completion__range=( period_start, period_end)).values('timestamp_completion') completed = np.array([ (job['timestamp_completion'] - period_start).days for job in jobs ]) counts[platform], bin_edges = np.histogram( completed, bins=np.arange(0, (period_end - period_start).days, interval)) for i, days in enumerate(bin_edges[:-1]): count = {} start = period_start + timedelta( int(days)) # timedelta doesn't like numpy int64 end = start + timedelta(interval) for platform in counts: count[platform] = counts[platform][i] new_obj = DateRangeCount(start, end, count) results.append(new_obj) return results
class QuotaUsageResource(StatisticsResource): """ Cumulative quota usage """ start_date = fields.DateField(attribute="start_date") end_date = fields.DateField(attribute="end_date") counts = fields.DictField(attribute="counts") class Meta: resource_name = "statistics/resource-usage" list_allowed_methods = ['get'] detail_allowed_methods = [] def get_object_list(self, request): if "start" in request.GET: period_start = datetime(*map(int, request.GET["start"].split("-")), tzinfo=pytz.UTC) period_end = datetime(*map(int, request.GET["end"].split("-")), tzinfo=pytz.UTC) else: today = date.today() period_end = datetime(today.year, today.month, today.day, tzinfo=pytz.UTC) period_start = period_end - timedelta(30) interval = int(request.GET.get("interval", 7)) assert isinstance(period_start, datetime) assert isinstance(period_end, datetime) assert isinstance(interval, int) results = [] counts = defaultdict(lambda: 0.0) n_bins = (period_end - period_start).days//interval + 1 for platform in STANDARD_QUEUES: jobs = Job.objects.filter(status__in=('finished', 'error'), hardware_platform=platform, timestamp_completion__range=(period_start, period_end) ).values('timestamp_completion', 'resource_usage') completed = np.array([(job['timestamp_completion'] - period_start).days for job in jobs]) #counts[platform], bin_edges = np.histogram(completed, # bins=np.arange(0, (period_end - period_start).days, interval)) resource_usage = np.array([job['resource_usage'] for job in jobs]) index = completed//interval counts[platform] = np.zeros((n_bins,)) for i, usage in zip(index, resource_usage): if usage is not None: counts[platform][i] += usage count_cumul = defaultdict(lambda: 0.0) for i in range(n_bins): start = period_start + timedelta(i * interval) end = start + timedelta(interval) for platform in STANDARD_QUEUES: count_cumul[platform] += counts[platform][i] new_obj = DateRangeCount(start, end, count_cumul) results.append(new_obj) return results
class InvoiceRevisionResource(BaseRevisionResource): invoicing_date = base_fields.DateField( attribute='invoicing_date', null=True, blank=True, help_text=HELP_TEXT['invoice_revision']['invoicing_date']) due_date = base_fields.DateField( attribute='due_date', null=True, blank=True, help_text=HELP_TEXT['invoice_revision']['due_date']) class Meta(VosaeResource.Meta): object_class = InvoiceRevision
class QuotationRevisionResource(BaseRevisionResource): quotation_date = base_fields.DateField( attribute='quotation_date', null=True, blank=True, help_text=HELP_TEXT['quotation_revision']['quotation_date']) quotation_validity = base_fields.DateField( attribute='quotation_validity', null=True, blank=True, help_text=HELP_TEXT['quotation_revision']['quotation_validity']) class Meta(VosaeResource.Meta): object_class = QuotationRevision
class SurveyReportResource(SurveyDashResource): questions = fields.ToManyField(QuestionResource, 'questions', null=True, blank=True, full=True) activity_points = fields.IntegerField(attribute='activity_points', readonly=True) response_date_start = fields.DateField(attribute='response_date_start', readonly=True, null=True, blank=True) response_date_end = fields.DateField(attribute='response_date_end', readonly=True, null=True, blank=True)
class EventResource(ModelResource): def get_url(self, bundle): return reverse('registration.views.event', kwargs={ 'club_name': bundle.obj.season.club.safe_name, 'season_year': bundle.obj.season.year, 'event_name': bundle.obj.safe_name }) name = fields.CharField(attribute='name') date = fields.DateField(attribute='date') location = fields.ToOneField('garage.api.LocationResource', 'location', blank=True, null=True) season = fields.ToOneField('garage.api.SeasonResource', 'season') club = fields.ToOneField('garage.api.ClubResource', 'club') club_name = fields.CharField(null=True, readonly=True) url = fields.CharField(null=True, readonly=True) class Meta: authentication = SessionAuthentication() authorization = ClubAdminAuthorization() queryset = Event.objects.all().select_related() resource_name = "event" def dehydrate(self, bundle): bundle.data['club_name'] = bundle.obj.season.club.name bundle.data['url'] = self.get_url(bundle) return bundle
class QuestionsResource(CachedResource): """Returns metrics related to questions. * Number of questions asked * Number of questions responded to within 72 hours * Number of questions solved """ date = fields.DateField('date') questions = fields.IntegerField('questions', default=0) responded = fields.IntegerField('responded', default=0) solved = fields.IntegerField('solved', default=0) def get_object_list(self, request): # Set up the query for the data we need. qs = _daily_qs_for(Question) # All answers tht were created within 3 days of the question. aq = Answer.objects.filter( created__lt=F('question__created') + timedelta(days=3)) # Questions of said answers. rs = qs.filter(id__in=aq.values_list('question')) # Questions with a solution. qs_with_solutions = qs.filter(solution__isnull=False) return merge_results( questions=qs, solved=qs_with_solutions, responded=rs) class Meta(object): cache = SimpleCache() resource_name = 'kpi_questions' allowed_methods = ['get']
class VoteResource(CachedResource): """Returns the number helpful votes for Articles and Answers.""" date = fields.DateField('date') kb_helpful = fields.IntegerField('kb_helpful', default=0) kb_votes = fields.IntegerField('kb_votes', default=0) ans_helpful = fields.IntegerField('ans_helpful', default=0) ans_votes = fields.IntegerField('ans_votes', default=0) def get_object_list(self, request): # Set up the queries for the data we need qs_kb_votes = _qs_for(HelpfulVote) qs_ans_votes = _qs_for(AnswerVote) # Filter on helpful qs_kb_helpful_votes = qs_kb_votes.filter(helpful=True) qs_ans_helpful_votes = qs_ans_votes.filter(helpful=True) return merge_results( kb_votes=qs_kb_votes, kb_helpful=qs_kb_helpful_votes, ans_votes=qs_ans_votes, ans_helpful=qs_ans_helpful_votes) class Meta(object): cache = SimpleCache() resource_name = 'kpi_vote' allowed_methods = ['get']
class KBVoteResource(CachedResource): """Returns the number helpful votes for KB Articles.""" date = fields.DateField('date') kb_helpful = fields.IntegerField('kb_helpful', default=0) kb_votes = fields.IntegerField('kb_votes', default=0) def get_object_list(self, request): # Set up the queries for the data we need locale = request.GET.get('locale') qs_kb_votes = HelpfulVote.objects.filter(created__gte=date(2011, 1, 1)) if locale: qs_kb_votes = qs_kb_votes.filter(revision__document__locale=locale) qs_kb_votes = (qs_kb_votes.extra( select={ 'day': 'extract( day from wiki_helpfulvote.created )', 'month': 'extract( month from wiki_helpfulvote.created )', 'year': 'extract( year from wiki_helpfulvote.created )', }).values('year', 'month', 'day').annotate(count=Count('created'))) # Filter on helpful qs_kb_helpful_votes = qs_kb_votes.filter(helpful=True) return merge_results(kb_votes=qs_kb_votes, kb_helpful=qs_kb_helpful_votes) class Meta(object): cache = SimpleCache() resource_name = 'kpi_kb_vote' allowed_methods = ['get']
class MakerSciencePostResourceLight(ModelResource, SearchableMakerScienceResource): slug = fields.CharField('parent__slug') parent_id = fields.IntegerField('parent__id') updated_on = fields.DateField('parent__updated_on') title = fields.CharField('parent__title') answers_count = fields.IntegerField('parent__answers_count') tags = fields.ToManyField(TaggedItemResource, 'parent__tagged_items', full=True, null=True) class Meta: queryset = MakerSciencePost.objects.all() allowed_methods = ['get'] resource_name = 'makerscience/postlight' authentication = AnonymousApiKeyAuthentication() authorization = MakerSciencePostAuthorization() always_return_data = True filtering = { 'post_type': ['exact'], 'parent_id': ['exact'], 'id': ['exact'], } def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/search%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('ms_search'), name="api_ms_search"), ]
class CumulativeUserCountResource(StatisticsResource): """ Cumulative number of platform users """ dates = fields.DateField(attribute="dates") values = fields.ListField(attribute="values") class Meta: resource_name = "statistics/cumulative-user-count" list_allowed_methods = [] detail_allowed_methods = ['get'] def obj_get(self, bundle, **kwargs): users = Job.objects.values("user_id").distinct() first_job_dates = [] for n, user in enumerate(users): user_id = user['user_id'] first_job_dates.append(Job.objects.filter(user_id=user_id).first().timestamp_submission.date()) first_job_dates.append(date.today()) user_counts = list(range(1, len(users) + 1)) user_counts.append(user_counts[-1]) # repeat last value for today's date return TimeSeries(dates=sorted(first_job_dates), values=user_counts) def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), ]
class ExerciseResource(ModelResource): category = fields.ToOneField('wger.exercises.api.resources.ExerciseCategoryResource', 'category') muscles = fields.ToManyField('wger.exercises.api.resources.MuscleResource', 'muscles') muscles_secondary = fields.ToManyField('wger.exercises.api.resources.MuscleResource', 'muscles_secondary') comments = fields.ToManyField('wger.exercises.api.resources.ExerciseCommentResource', 'exercisecomment_set') images = fields.ToManyField('wger.exercises.api.resources.ExerciseImageResource', 'exerciseimage_set') equipment = fields.ToManyField('wger.exercises.api.resources.EquipmentResource', 'equipment') language = fields.ToOneField(LanguageResource, 'language') license = fields.ToOneField(LicenseResource, 'license') creation_date = fields.DateField(attribute='creation_date', null=True) class Meta: queryset = Exercise.objects.all() filtering = {'id': ALL, "uuid": ALL, "category": ALL_WITH_RELATIONS, "creation_date": ALL, "description": ALL, "images": ALL_WITH_RELATIONS, "language": ALL_WITH_RELATIONS, "muscles": ALL_WITH_RELATIONS, "status": ALL, "name": ALL, "license": ALL, "license_author": ALL}
class ContactResource(EntityResource, VosaeIMEXMixinResource): name = base_fields.CharField(attribute='name', help_text=HELP_TEXT['contact']['name']) firstname = base_fields.CharField( attribute='firstname', help_text=HELP_TEXT['contact']['firstname']) additional_names = base_fields.CharField( attribute='additional_names', null=True, blank=True, help_text=HELP_TEXT['contact']['additional_names']) civility = base_fields.CharField( attribute='civility', null=True, blank=True, help_text=HELP_TEXT['contact']['civility']) birthday = base_fields.DateField( attribute='birthday', null=True, blank=True, help_text=HELP_TEXT['contact']['birthday']) role = base_fields.CharField(attribute='role', null=True, blank=True, help_text=HELP_TEXT['contact']['role']) organization = fields.ReferenceField( to='contacts.api.resources.OrganizationResource', attribute='organization', null=True, blank=True, full=False, help_text=HELP_TEXT['contact']['organization']) class Meta(EntityResource.Meta): queryset = Contact.objects.all() def prepend_urls(self): """Add urls for resources import/export.""" urls = super(ContactResource, self).prepend_urls() urls.extend(VosaeIMEXMixinResource.prepend_urls(self)) return urls def do_import(self, request, serializer, import_buffer): """Contacts import""" try: return serializer.deserialize(import_buffer, self._meta.object_class, request.tenant) except: pass def do_export(self, request, serializer, export_objects): """Contacts export""" if len(export_objects) == 1: filename = export_objects[0].get_full_name() else: filename = _('Contacts') return serializer.serialize(export_objects), filename
class MessageResource(ModelResource): description = fields.CharField(attribute='description', help_text='A public description of the message') message = fields.CharField(attribute='message', help_text='The hidden messsage.') time_to_reveal = fields.DateField(help_text='Time in seconds until reveal.') code = fields.CharField(attribute='code', readonly=True, help_text="The public code to id the message") admin_code = fields.CharField(attribute='admin_code', help_text="A private code to enter the message admin page.") class Meta: queryset = Message.objects.all() authorization = Authorization() excludes = ['opened','readed','id', 'reveal_on'] resource_class = Message examples = { 'POST' : { 'description' : 'bla bla', 'message' : 'el mensaje', 'time_to_reveal' : 4000, }, 'GET' : { 'description' : 'bla bla', 'message' : 'el mensaje', 'time_to_reveal' : 4000, 'code' : 'HGFSCVZSA2B', 'resource_id' : '/api/resources/message/1/', } } def obj_update(self, bundle, request=None, **kwargs): try: del bundle.data['admin_code'] except KeyError: pass return super(MessageResource, self).obj_update(bundle, request, **kwargs) def hydrate_time_to_reveal(self, bundle): now = datetime.now() ttr = int(bundle.data['time_to_reveal']) delta = timedelta(seconds=ttr) bundle.obj.reveal_on = now + delta return bundle def full_dehydrate(self, bundle): bundle = super(MessageResource, self).full_dehydrate(bundle) now = datetime.now() if bundle.obj.reveal_on > now: bundle.data['message'] = "" del bundle.data['admin_code'] revealDate = bundle.obj.reveal_on now = datetime.now() if now > revealDate: bundle.data['time_to_reveal'] = 0 else : delta = revealDate - now bundle.data['time_to_reveal'] = delta.seconds return bundle
class PurchaseOrderRevisionResource(BaseRevisionResource): purchase_order_date = base_fields.DateField( attribute='purchase_order_date', null=True, blank=True, help_text=HELP_TEXT['purchase_order_revision']['purchase_order_date']) class Meta(VosaeResource.Meta): object_class = PurchaseOrderRevision
class CollectionResource(ModelResource): date_created = fields.DateField('date_created') date_updated = fields.DateField('date_updated') user = fields.CharField('user__username') name = fields.CharField('name') description = fields.CharField('description') images = fields.ToManyField(ImageResource, 'images') class Meta: authentication = AppAuthentication() allowed_methods = ['get'] queryset = Collection.objects.all() filtering = { 'name': ALL, 'description': ALL, 'user': ALL_WITH_RELATIONS, } ordering = ['-date_created']
class ActiveUserCountResource(StatisticsResource): """ Number of platform users who have submitted at least one job in the last 90 days """ start_date = fields.DateField(attribute="start_date") end_date = fields.DateField(attribute="end_date") counts = fields.DictField(attribute="counts") class Meta: resource_name = "statistics/active-user-count" list_allowed_methods = ['get'] detail_allowed_methods = [] def get_object_list(self, request): if "start" in request.GET: period_start = datetime(*map(int, request.GET["start"].split("-")), tzinfo=pytz.UTC) period_end = datetime(*map(int, request.GET["end"].split("-")), tzinfo=pytz.UTC) else: today = date.today() period_end = datetime(today.year, today.month, today.day, tzinfo=pytz.UTC) period_start = period_end - timedelta(30) interval = int(request.GET.get("interval", 7)) date_list = list(daterange(period_start, period_end, interval)) date_list.append(period_end) results = [] for end in date_list[:-1]: start = end - timedelta(90) active_users = {} for platform in STANDARD_QUEUES: active_users[platform] = Job.objects.filter( hardware_platform=platform, timestamp_completion__range=( start, end)).values("user_id").distinct().count() # note that the "total" value may be less than the sum of the per-platform values, since some users use multiple platforms #active_users["total"] = Job.objects.filter(timestamp_completion__range=(start, end)).values("user_id").distinct().count() new_obj = DateRangeCount(start, end, active_users) results.append(new_obj) return results
class ExportResource(TenantResource): created_at = base_fields.DateTimeField( attribute='created_at', readonly=True, help_text=HELP_TEXT['export']['created_at']) language = base_fields.CharField(attribute='language', help_text=HELP_TEXT['export']['language']) documents_types = base_fields.ListField( attribute='documents_types', help_text=HELP_TEXT['export']['documents_types']) from_date = base_fields.DateField( attribute='from_date', null=True, blank=True, help_text=HELP_TEXT['export']['from_date']) to_date = base_fields.DateField(attribute='to_date', null=True, blank=True, help_text=HELP_TEXT['export']['to_date']) issuer = fields.ReferenceField(to='core.api.resources.VosaeUserResource', attribute='issuer', readonly=True, help_text=HELP_TEXT['export']['issuer']) zipfile = fields.ReferenceField(to='core.api.resources.VosaeFileResource', attribute='zipfile', readonly=True, null=True, help_text=HELP_TEXT['export']['zipfile']) class Meta(TenantResource.Meta): resource_name = 'export' queryset = Export.objects.all() list_allowed_methods = ('get', 'post', 'delete') detail_allowed_methods = ('get', 'delete') excludes = ('tenant', ) def hydrate(self, bundle): """Set issuer on POST, extracted from request""" bundle = super(ExportResource, self).hydrate(bundle) bundle.obj.issuer = bundle.request.vosae_user return bundle
class ObservationResource(MongoResource): #author = fields.ApiField(attribute='author') city = fields.CharField(attribute='loc_city', null=True) country = fields.CharField(attribute='loc_country', null=True) start = fields.DateField(attribute='start', null=True) finish = fields.DateField(attribute='finish', null=True) duration = fields.IntegerField(attribute='duration', null=True) no_smoking = fields.IntegerField(attribute='no_smoking', null=True) lone_adult = fields.IntegerField(attribute='lone_adult', null=True) other_adults = fields.IntegerField(attribute='other_adults', null=True) child = fields.IntegerField(attribute='child', null=True) longitude = fields.FloatField(attribute='longitude') latitude = fields.FloatField(attribute='latitude') class Meta: resource_name = 'observation' authorization = Authorization() authentication = Authentication() filtering = { 'no_smoking': ['exact', 'gt', 'gte', 'lt', 'lte'], 'lone_adult': ['exact', 'gt', 'gte', 'lt', 'lte'], 'other_adults': ['exact', 'gt', 'gte', 'lt', 'lte'], 'child': ['exact', 'gt', 'gte', 'lt', 'lte'], 'start': ['exact', 'gt', 'gte', 'lt', 'lte'], 'finish': ['exact', 'gt', 'gte', 'lt', 'lte'], 'duration': ['exact', 'gt', 'gte', 'lt', 'lte'], 'city': ['exact', 'startswith', 'contains', 'endswith'], 'country': ['exact', 'startswith', 'contains', 'endswith'], 'latitude': ['exact', 'gt', 'gte', 'lt', 'lte'], 'longitude': ['exact', 'gt', 'gte', 'lt', 'lte'], } def get_object_list(self, request): return Observation.objects def obj_get(self, request=None, **kwargs): print kwargs pk = kwargs['pk'] obs = Observation.objects.get(id=pk) return obs
class CreditNoteRevisionResource(BaseRevisionResource): credit_note_emission_date = base_fields.DateField( attribute='credit_note_emission_date', readonly=True, null=True, blank=True, help_text=HELP_TEXT['credit_note_revision'] ['credit_note_emission_date']) class Meta(VosaeResource.Meta): object_class = CreditNoteRevision
class CumulativeJobCountResource(StatisticsResource): """ Cumulative number of jobs for each backend in a given time period """ start_date = fields.DateField(attribute="start_date") end_date = fields.DateField(attribute="end_date") counts = fields.DictField(attribute="counts") class Meta: resource_name = "statistics/cumulative-job-count" list_allowed_methods = ['get'] detail_allowed_methods = [] def get_object_list(self, request): if "start" in request.GET: period_start = datetime(*map(int, request.GET["start"].split("-")), tzinfo=pytz.UTC) period_end = datetime(*map(int, request.GET["end"].split("-")), tzinfo=pytz.UTC) else: today = date.today() period_end = datetime(today.year, today.month, today.day, tzinfo=pytz.UTC) period_start = period_end - timedelta(30) interval = int(request.GET.get("interval", 1)) date_list = list(daterange(period_start, period_end, interval)) date_list.append(period_end) results = [] job_counts = Counter() for start, end in zip(date_list[:-1], date_list[1:]): for platform in STANDARD_QUEUES: job_counts[platform] += Job.objects.filter( status__in=('finished', 'error'), hardware_platform=platform, timestamp_completion__range=(start, end)).count() new_obj = DateRangeCount(start, end, job_counts) results.append(new_obj) return results
class Album(resources.ModelResource): class Meta(BaseMeta): queryset = models.Album.objects.all() resource_name = 'album' filtering = { 'item': ALL_WITH_RELATIONS, } ordering = ('item', ) item = fields.ForeignKey(Item, 'item') release_date = fields.DateField('release_date')
class ActiveContributorsResource(CachedResource): """Returns the number of active contributors. * en-US KB contributors * non-en-US contributors * Support Forum contributors * Army of Awesome contributors """ date = fields.DateField('date') en_us = fields.IntegerField('en_us', default=0) non_en_us = fields.IntegerField('non_en_us', default=0) support_forum = fields.IntegerField('support_forum', default=0) aoa = fields.IntegerField('aoa', default=0) def get_object_list(self, request): # Set up the queries for the data we need kind = MetricKind.objects.get(code=KB_ENUS_CONTRIBUTORS_METRIC_CODE) en_us = Metric.objects.filter(kind=kind).order_by('-start') kind = MetricKind.objects.get(code=KB_L10N_CONTRIBUTORS_METRIC_CODE) l10n = Metric.objects.filter(kind=kind).order_by('-start') kind = MetricKind.objects.get( code=SUPPORT_FORUM_CONTRIBUTORS_METRIC_CODE) answers = Metric.objects.filter(kind=kind).order_by('-start') kind = MetricKind.objects.get(code=AOA_CONTRIBUTORS_METRIC_CODE) aoa = Metric.objects.filter(kind=kind).order_by('-start') # Put all the results in a dict with the date as the key. results_dict = {} def merge_results(metrics_qs, label): for metric in metrics_qs: results_dict.setdefault(metric.end, {})[label] = metric.value merge_results(en_us, 'en_us') merge_results(l10n, 'non_en_us') merge_results(answers, 'support_forum') merge_results(aoa, 'aoa') # Convert that to a list of dicts. results_list = [dict(date=k, **v) for k, v in results_dict.items()] return [ Struct(**x) for x in sorted(results_list, key=itemgetter('date'), reverse=True) ] class Meta: cache = SimpleCache() resource_name = 'kpi_active_contributors' allowed_methods = ['get']
class TopPickResource(ModelResource): image = fields.ForeignKey('astrobin.api.ImageResource', 'image') date = fields.DateField('date') class Meta: authentication = AppAuthentication() queryset = IotdVote.objects.all() fields = [ 'image', 'date' ] allowed_methods = ['get']
class TopPickResource(ModelResource): image = fields.ForeignKey('astrobin.api.ImageResource', 'image') date = fields.DateField('date') class Meta: authentication = AppAuthentication() queryset = IotdVote.objects.filter(image__corrupted=False) fields = ['image', 'date'] allowed_methods = ['get'] def dehydrate_image(self, bundle): return "/api/v1/image/%s" % bundle.obj.image.get_id()
class MetadataInfoResource(ModelResource): class Meta: queryset = lr.metadataInfoType_model.objects.all() resource_name = "metadataInfo" allowed_methods = ['get'] fields = ['metadataCreationDate'] include_resource_uri = False filtering = { 'metadataCreationDate': ALL, } metadataCreationDate = fields.DateField(attribute='metadataCreationDate', verbose_name='created')
class CollectionResource(ModelResource): date_created = fields.DateField('date_created') date_updated = fields.DateField('date_updated') user = fields.CharField('user__username') name = fields.CharField('name') description = fields.CharField('description') images = fields.ToManyField(ImageResource, 'images') class Meta: authentication = AppAuthentication() allowed_methods = ['get'] queryset = Collection.objects.all() filtering = { 'name': ALL, 'description': ALL, 'user': ALL_WITH_RELATIONS, } ordering = ['-date_created'] def dehydrate_images(self, bundle): images = bundle.obj.images.all() return ["/api/v1/image/%s" % image.get_id() for image in images]
class QuestionsResource(CachedResource): """Returns metrics related to questions. * Number of questions asked * Number of questions responded to within 72 hours * Number of questions solved """ date = fields.DateField('date') questions = fields.IntegerField('questions', default=0) responded_72 = fields.IntegerField('responded_72', default=0) responded_24 = fields.IntegerField('responded_24', default=0) solved = fields.IntegerField('solved', default=0) def get_object_list(self, request): locale = request.GET.get('locale') # Set up the query for the data we need. qs = _daily_qs_for(Question) # Don't count locked questions qs = qs.exclude(is_locked=True) if locale: qs = qs.filter(locale=locale) # All answers that were created within 3 days of the question. aq_72 = Answer.objects.filter(created__lt=F('question__created') + timedelta(days=3)) # Questions of said answers. rs_72 = qs.filter(id__in=aq_72.values_list('question')) # All answers that were created within 24 hours of the question. aq_24 = Answer.objects.filter(created__lt=F('question__created') + timedelta(hours=24)) # Questions of said answers. rs_24 = qs.filter(id__in=aq_24.values_list('question')) # Questions with a solution. qs_with_solutions = qs.exclude(solution_id=None) return merge_results(questions=qs, solved=qs_with_solutions, responded_72=rs_72, responded_24=rs_24) class Meta(object): cache = SimpleCache() resource_name = 'kpi_questions' allowed_methods = ['get']
class StockResource(ModelResource): symbol = fields.CharField("symbol") tax_rate = fields.FloatField("tax_rate", null=True, use_in="detail") latest_close_price = fields.FloatField("latest_close_price", null=True, use_in="detail") dupont_model = fields.ListField("dupont_model", null=True, use_in="detail") nav_model = fields.ListField("nav_model", null=True, use_in="detail") dupont_roe = fields.FloatField("dupont_roe", null=True, use_in="detail") roe_dupont_reported_gap = fields.FloatField("roe_dupont_reported_gap", null=True, use_in="detail") last_reporting_date = fields.DateField("last_reporting_date", null=True) dcf_model = fields.ListField("dcf_model", null=True, use_in="detail") sectors = fields.ManyToManyField("stock.api.SectorResource", "sectors", null=True) class Meta: queryset = MyStock.objects.all() resource_name = "stocks" filtering = {"symbol": ALL, "id": ALL} authorization = Authorization() limit = 0 max_limit = 0 def obj_update(self, bundle, **kwargs): stock = bundle.obj symbol = stock.symbol sectors = stock.sectors.all() if sectors: sector = sectors[0].name else: sector = "misc" # kick off updates batch_update_helper(sector, symbol) def obj_create(self, bundle, **kwargs): sector, created = MySector.objects.get_or_create(name="misc") stock, created = MyStock.objects.get_or_create( symbol=bundle.data["symbol"]) sector.stocks.add(stock) # kick off updates batch_update_helper(sector.name, stock.symbol) bundle.obj = stock return bundle