コード例 #1
0
class WebVideoResource(MultipartResource, ModelResource):
    video = fields.FileField(attribute="video")
    versions = fields.OneToManyField(ConvertedVideoResource, 'converted', full=True, null=True, blank=True)

    class Meta:
        queryset = WebVideo.objects.all()
        resource_name = 'video'
        fields = ['id', 'versions', 'duration', 'video', ]
        allowed_methods = ['get', 'post', ]

        filtering = {
            'duration': ['exact', 'gt', 'gte', 'lt', 'lte', 'range'],
        }

        authentication = WebVideoAuthentication()
        authorization = WebVideoAuthorization()
        cache = SimpleCache(timeout=300)
        throttle = CacheThrottle(throttle_at=50, timeframe=60)
        serializer = Serializer(formats=['json', ])
コード例 #2
0
ファイル: resources.py プロジェクト: Persice/persice.com
class EventResourceSmall(ModelResource):
    members = fields.OneToManyField('events.api.resources.MembershipResource',
                                    attribute=lambda bundle:
                                    bundle.obj.membership_set.all(),
                                    full=True, null=True)

    class Meta:
        always_return_data = True
        queryset = Event.objects.all().order_by('-starts_on')
        resource_name = 'event'
        excludes = ['search_index']

        filtering = {
            'description': ALL
        }
        validation = EventValidation()
        authentication = JSONWebTokenAuthentication()
        authorization = GuardianAuthorization(
            view_permission_code='view_event'
        )
コード例 #3
0
ファイル: api.py プロジェクト: kansanmuisti/kamu
class PlenarySessionItemResource(KamuResource):
    plenary_session = fields.ForeignKey(PlenarySessionResource, 'plsess')
    documents = fields.ManyToManyField('parliament.api.DocumentResource',
                                       'docs',
                                       full=False)
    plenary_votes = fields.OneToManyField('parliament.api.PlenaryVoteResource',
                                          'plenary_votes',
                                          full=False,
                                          null=True)

    class Meta:
        queryset = PlenarySessionItem.objects.order_by('number', 'sub_number')
        resource_name = 'plenary_session_item'
        filtering = {
            'plenary_session': ALL_WITH_RELATIONS,
            'processing_stage': ALL,
            'nr_votes': ALL,
            'nr_statements': ALL,
        }
        ordering = ['plenary_session']
コード例 #4
0
ファイル: resources.py プロジェクト: rerb/stars
class SubcategoryResource(StarsApiResource):
    """
        Resource for accessing any Subcategory
    """
    category = fields.ForeignKey(CREDITS_RESOURCE_PATH +
                                 'NestedCategoryResource',
                                 'category',
                                 full=True)
    credits = fields.OneToManyField(CREDITS_RESOURCE_PATH +
                                    'NestedCreditResource',
                                    'credit_set',
                                    related_name='subcategory',
                                    full=True)

    class Meta(StarsApiResource.Meta):
        authentication = Authentication()
        queryset = credits_models.Subcategory.objects.all()
        resource_name = 'credits/subcategory'
        allowed_methods = ['get']
        excludes = ['max_point_value']
コード例 #5
0
class SectionResource(ModelResource):
    journal = fields.ForeignKey('api.resources_v2.JournalResource', 'journal')
    issues = fields.OneToManyField('api.resources_v2.IssueResource',
                                   'issue_set')
    titles = fields.CharField(readonly=True)

    class Meta(ApiKeyAuthMeta):
        queryset = models.Section.objects.all()
        resource_name = 'sections'
        allowed_methods = ['get']
        excludes = ['legacy_code']
        filtering = {
            "journal": ('exact'),
        }

    def build_filters(self, filters=None):
        """
        Custom filter that retrieves data by journal eletronic_issn and print_issn.
        """
        if filters is None:
            filters = {}

        orm_filters = super(SectionResource, self).build_filters(filters)

        param_filters = {}

        if 'journal_eissn' in filters:
            param_filters['journal__eletronic_issn'] = filters['journal_eissn']

        if 'journal_pissn' in filters:
            param_filters['journal__print_issn'] = filters['journal_pissn']

        sections = models.Section.objects.filter(**param_filters)

        orm_filters['pk__in'] = sections

        return orm_filters

    def dehydrate_titles(self, bundle):
        return dict([title.language.iso_code, title.title]
                    for title in bundle.obj.titles.all())
コード例 #6
0
class CollectionResource(ModelResource):
    campus = fields.ToManyField(CampusResource, 'campus', full=True)
    repository = fields.ToManyField(RepositoryResource,
                                    'repository',
                                    full=True)
    custom_facet = fields.OneToManyField(
        'library_collection.api.CustomFacetResource',
        'collectioncustomfacet_set',
        full=True)

    class Meta:
        queryset = Collection.objects.all()
        authentication = Authentication()
        authorization = ReadOnlyAuthorization()
        serializer = Serializer(
            formats=['json', 'jsonp', 'xml', 'yaml', 'plist'])
        filtering = {
            "url_harvest": ('exact', 'startswith'),
            "slug": ALL,
            "harvest_type": ('exact'),
        }
コード例 #7
0
class AheadPressReleaseResource(ModelResource):
    journal_uri = fields.ForeignKey(JournalResource, 'journal')
    translations = fields.OneToManyField(PressReleaseTranslationResource,
                                         'translations',
                                         full=True)
    articles = fields.CharField(readonly=True)

    class Meta(ApiKeyAuthMeta):
        resource_name = 'apressreleases'
        queryset = AheadPressRelease.objects.all()
        allowed_methods = [
            'get',
        ]

    def dehydrate_articles(self, bundle):
        return [art.article_pid for art in bundle.obj.articles.all()]

    def build_filters(self, filters=None):
        """
        Custom filter that retrieves data by the article PID.
        """
        if filters is None:
            filters = {}

        orm_filters = super(AheadPressReleaseResource,
                            self).build_filters(filters)

        if 'article_pid' in filters:
            preleases = AheadPressRelease.objects.filter(
                articles__article_pid=filters['article_pid'])
            orm_filters['pk__in'] = preleases

        elif 'journal_pid' in filters:
            preleases = AheadPressRelease.objects.by_journal_pid(
                filters['journal_pid'])
            orm_filters['pk__in'] = preleases

        return orm_filters
コード例 #8
0
ファイル: resources.py プロジェクト: rerb/stars
class InstitutionResource(StarsApiResource):
    """
        Resource for accessing any Institution.
    """
    submission_sets = fields.OneToManyField(
       SUBMISSIONS_RESOURCE_PATH + "NestedSubmissionSetResource",
       'submissionset_set', full=True)
    current_report = fields.OneToOneField(
        SUBMISSIONS_RESOURCE_PATH + "NestedSubmissionSetResource",
        'rated_submission', full=True, null=True)
    postal_code = fields.CharField(readonly=True)
    city = fields.CharField(readonly=True)
    state = fields.CharField(readonly=True)

    class Meta(StarsApiResource.Meta):
        queryset = models.Institution.objects.get_rated().order_by('name')
        resource_name = 'institutions'
        fields = ['name', 'is_member', 'country']
        allowed_methods = ['get']

    def dehydrate_city(self, bundle):
        if bundle.obj.profile:
            return bundle.obj.profile.city

    def dehydrate_state(self, bundle):
        if bundle.obj.profile:
            return bundle.obj.profile.state

    def dehydrate_postal_code(self, bundle):
        if bundle.obj.profile:
            return bundle.obj.profile.postal_code

    def dehydrate_submission_sets(self, bundle):
        """Filter unrated submission sets."""
        rated_submissions = [ss for ss in bundle.data['submission_sets']
                             if ss.obj.rating]
        return rated_submissions
コード例 #9
0
ファイル: resources.py プロジェクト: Persice/persice.com
class EventResource(MultiPartResource, ModelResource):
    members = fields.OneToManyField('events.api.resources.MembershipResource',
                                    attribute=lambda bundle:
                                    bundle.obj.membership_set.all(),
                                    full=True, null=True)
    attendees = fields.OneToManyField(
        'events.api.resources.MembershipResource',
        attribute=lambda bundle:
        # TODO: fix user bundle.request.user.id
        #
        bundle.obj.membership_set.filter(
            user__in=NeoFourJ().get_my_friends_ids(bundle.request.user.id) +
            [bundle.request.user.id], rsvp='yes'),
        full=True, null=True)
    event_photo = fields.FileField(attribute="event_photo", null=True,
                                   blank=True)

    class Meta:
        always_return_data = True
        queryset = Event.objects.all().order_by('-starts_on')
        resource_name = 'event'
        excludes = ['search_index']

        filtering = {
            'description': ALL
        }
        validation = EventValidation()
        authentication = JSONWebTokenAuthentication()
        authorization = GuardianAuthorization(
            view_permission_code='view_event',
            # create_permission_code='add_event',
        )

    def dehydrate(self, bundle):
        user_id = bundle.request.user.id
        friends = NeoFourJ().get_my_friends_ids(user_id)
        try:
            bundle.data['hosted_by'] = bundle.obj.membership_set. \
                filter(is_organizer=True, rsvp='yes')[0].user.get_full_name()
        except IndexError:
            bundle.data['hosted_by'] = ''

        # Total number of event attendees
        total_attendees = bundle.obj. \
            membership_set.filter(rsvp='yes').count()
        bundle.data['total_attendees'] = total_attendees

        # the number of people with RSVP = yes AND
        # are also a connection of the user who is viewing the event
        attendees = bundle.obj. \
            membership_set.filter(user__in=friends + [user_id], rsvp='yes')
        bundle.data['friend_attendees_count'] = attendees.count()

        # spots_remaining = max_attendees - total_attendees
        # TODO: max_attendees in ICE-938
        bundle.data['spots_remaining'] = int(
            bundle.obj.max_attendees) - total_attendees

        matched_users = MatchQuerySet.attendees(user_id)
        bundle.data['attendees_yes'] = MatchEvent.get_attendees(
            user_id, bundle.obj, matched_users, rsvp='yes')
        bundle.data['attendees_no'] = MatchEvent.get_attendees(
            user_id, bundle.obj, matched_users, rsvp='no')
        bundle.data['attendees_maybe'] = MatchEvent.get_attendees(
            user_id, bundle.obj, matched_users, rsvp='maybe')

        bundle.data['cumulative_match_score'] = MatchEvent.get_cum_score(
            user_id, bundle.obj, matched_users)

        try:
            bundle.data['distance'] = MatchQuerySet.user_event(
                    bundle.request.user.id,
                    bundle.obj.pk
            )[0].distance
        except IndexError:
            bundle.data['distance'] = [10000, 'mi']
        bundle.data['organizer'] = build_organizer(bundle.obj)
        return bundle

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/search%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_search'), name="api_get_search"),
        ]

    def get_search(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        # Do the query.
        query = request.GET.get('q', '')
        sqs = SearchQuerySet().models(Event).load_all(). \
            filter(SQ(name=query) | SQ(description=query))
        paginator = Paginator(sqs, 10)

        try:
            page = paginator.page(int(request.GET.get('page', 1)))
        except InvalidPage:
            raise Http404("Sorry, no results on that page.")

        objects = []

        for result in page.object_list:
            bundle = self.build_bundle(obj=result.object, request=request)
            bundle = self.full_dehydrate(bundle)
            objects.append(bundle)

        object_list = {
            'objects': objects,
        }

        self.log_throttled_access(request)
        return self.create_response(request, object_list)

    def obj_create(self, bundle, **kwargs):
        bundle = super(EventResource, self).obj_create(bundle, **kwargs)
        assign_perm('view_event', bundle.request.user, bundle.obj)
        Membership.objects.create(user=bundle.request.user, event=bundle.obj,
                                  is_organizer=True, rsvp='yes')

        if bundle.obj.access_level == 'public':
            users = FacebookCustomUserActive.objects.all(). \
                exclude(pk=bundle.request.user.id)
            assign_perm_task.delay('view_event', users, bundle.obj)
        elif bundle.obj.access_level == 'private':
            if bundle.obj.access_user_list:
                try:
                    user_ids = map(int, bundle.obj.access_user_list.split(','))
                    users = FacebookCustomUserActive.objects.\
                        filter(pk__in=user_ids)
                    assign_perm_task.delay('view_event', users, bundle.obj)
                except TypeError as e:
                    logger.error(e)
        elif bundle.obj.access_level == 'connections':
            user_ids = []
            if bundle.obj.access_user_list:
                try:
                    user_ids = map(int, bundle.obj.access_user_list.split(','))
                except TypeError as e:
                    logger.error(e)
            else:
                user_ids = NeoFourJ().get_my_friends_ids(bundle.request.user.id)

            users = FacebookCustomUserActive.objects.filter(pk__in=user_ids)
            assign_perm_task.delay('view_event', users, bundle.obj)

        return bundle

    def obj_update(self, bundle, skip_errors=False, **kwargs):
        new_access_level = bundle.data.get('access_level', '')
        current_access_level = bundle.obj.access_level
        event_photo = bundle.data.get('event_photo', '')
        if isinstance(event_photo, unicode) and event_photo.startswith('http'):
            bundle.data['event_photo'] = \
                event_photo.split('cloudfront.net/')[-1]
        bundle = super(EventResource, self).obj_update(bundle, **kwargs)
        if current_access_level != new_access_level:
            if new_access_level == 'public':
                users = FacebookCustomUserActive.objects.all(). \
                    exclude(pk=bundle.request.user.id)
                assign_perm_task.delay('view_event', users, bundle.obj)

            elif new_access_level == 'private':
                users = FacebookCustomUserActive.objects.all(). \
                    exclude(pk=bundle.request.user.id)
                remove_perm_task.delay('view_event', users, bundle.obj)

                if bundle.obj.access_user_list:
                    try:
                        user_ids = map(int,
                                       bundle.obj.access_user_list.split(','))
                        users_ = FacebookCustomUserActive.objects. \
                            filter(pk__in=user_ids)
                        assign_perm_task.delay('view_event', users_, bundle.obj)
                    except TypeError as e:
                        logger.error(e)

            elif new_access_level == 'connections':
                users = FacebookCustomUserActive.objects.all(). \
                    exclude(pk=bundle.request.user.id)
                remove_perm_task.delay('view_event', users, bundle.obj)

                user_ids = []
                if bundle.obj.access_user_list:
                    try:
                        user_ids = map(int,
                                       bundle.obj.access_user_list.split(','))
                    except TypeError as e:
                        logger.error(e)
                else:
                    user_ids = NeoFourJ().get_my_friends_ids(
                        bundle.request.user.id
                    )

                users_ = FacebookCustomUserActive.objects. \
                    filter(pk__in=user_ids)
                assign_perm_task.delay('view_event', users_, bundle.obj)
        return bundle

    def obj_delete(self, bundle, **kwargs):
        r = redis.StrictRedis(host='localhost', port=6379, db=0)
        event = Event.objects.get(pk=int(kwargs['pk']))
        members = event.membership_set.filter(rsvp__in=['yes', 'maybe'],
                                              is_organizer=False)
        organizer = event.membership_set.filter(is_organizer=True)[0]
        recipients = FacebookCustomUserActive.objects. \
            filter(id__in=members.values_list('user_id', flat=True))
        data = {u'event_name': unicode(event.name),
                u'event_start_date': unicode(event.starts_on),
                u'event_organizer_name': unicode(organizer.user.first_name)}

        for recipient in recipients:
            message_data = {u'sent_at': now().isoformat(),
                            u'sender': '/api/auth/user/{}/'.format(
                                organizer.user.id),
                            u'recipient': '/api/auth/user/{}/'.format(
                                recipient.id),
                            u'body': u"""
                                    The event {event_name} on {event_start_date} has been
                                    cancelled by {event_organizer_name},
                                    the event host. We apologize for any inconvenience.
                                    (This is an automated message.)"
                                    """.format(**data)}
            pm_write(bundle.request.user, recipient, '',
                     body=message_data['body'])
            r.publish('message.%s' % recipient.id, json.dumps(message_data))

        for member in members:
            r.publish('event_deleted.%s' % member.user.id, json.dumps(data))

        return super(EventResource, self).obj_delete(bundle, **kwargs)

    def save_m2m(self, bundle):
        for field_name, field_object in self.fields.items():
            if not getattr(field_object, 'is_m2m', False):
                continue

            if not field_object.attribute:
                continue

            for field in bundle.data[field_name]:
                kwargs = {'event': Event.objects.get(pk=bundle.obj.id),
                          'user': field.obj.user}
                try:
                    Membership.objects.get_or_create(**kwargs)
                except IntegrityError:
                    continue

    def update_in_place(self, request, original_bundle, new_data):
        ends_on = original_bundle.data['ends_on']
        if ends_on < now():
            raise BadRequest(
                'Users cannot edit events which have an end date that '
                'occurred in the past.'
            )
        return super(EventResource, self).update_in_place(
            request, original_bundle, new_data
        )
コード例 #10
0
class PressReleaseResource(ModelResource):
    issue_uri = fields.ForeignKey(IssueResource, 'issue')
    translations = fields.OneToManyField(PressReleaseTranslationResource,
                                         'translations',
                                         full=True)
    articles = fields.CharField(readonly=True)
    issue_meta = fields.CharField(readonly=True)

    class Meta(ApiKeyAuthMeta):
        resource_name = 'pressreleases'
        queryset = RegularPressRelease.objects.all()
        allowed_methods = [
            'get',
        ]
        ordering = ['id']

    def build_filters(self, filters=None):
        """
        Custom filter that retrieves data by the article PID.
        """
        if filters is None:
            filters = {}

        orm_filters = super(PressReleaseResource, self).build_filters(filters)

        if 'article_pid' in filters:
            preleases = RegularPressRelease.objects.filter(
                articles__article_pid=filters['article_pid'])
            orm_filters['pk__in'] = preleases

        elif 'journal_pid' in filters:
            preleases = RegularPressRelease.objects.by_journal_pid(
                filters['journal_pid'])
            orm_filters['pk__in'] = preleases
        elif 'issue_pid' in filters:
            preleases = RegularPressRelease.objects.by_issue_pid(
                filters['issue_pid'])
            orm_filters['pk__in'] = preleases

        return orm_filters

    def dehydrate_articles(self, bundle):
        return [art.article_pid for art in bundle.obj.articles.all()]

    def dehydrate_issue_meta(self, bundle):
        issue = bundle.obj.issue

        meta_data = {
            'scielo_pid':
            issue.scielo_pid,
            'short_title':
            issue.journal.short_title,
            'volume':
            issue.volume,
            'number':
            issue.number,
            'suppl_volume':
            issue.suppl_text
            if issue.type == 'supplement' and issue.volume else '',
            'suppl_number':
            issue.suppl_text
            if issue.type == 'supplement' and issue.number else '',
            'publication_start_month':
            issue.publication_start_month,
            'publication_end_month':
            issue.publication_end_month,
            'publication_city':
            issue.journal.publication_city,
            'publication_year':
            issue.publication_year,
        }

        return meta_data
コード例 #11
0
class JournalResource(ModelResource):
    missions = fields.CharField(readonly=True)
    other_titles = fields.CharField(readonly=True)
    creator = fields.ForeignKey(UserResource, 'creator')
    abstract_keyword_languages = fields.CharField(readonly=True)
    languages = fields.CharField(readonly=True)
    use_license = fields.ForeignKey(UseLicenseResource,
                                    'use_license',
                                    full=True)
    sponsors = fields.ManyToManyField(SponsorResource, 'sponsor')
    collections = fields.ManyToManyField(CollectionResource, 'collections')
    issues = fields.OneToManyField(IssueResource, 'issue_set')
    sections = fields.OneToManyField(SectionResource, 'section_set')
    subject_categories = fields.ManyToManyField(SubjectCategoryResource,
                                                'subject_categories',
                                                readonly=True)
    pub_status_history = fields.ListField(readonly=True)
    contact = fields.DictField(readonly=True)
    study_areas = fields.ListField(readonly=True)
    pub_status = fields.CharField(readonly=True)
    pub_status_reason = fields.CharField(readonly=True)
    national_code = fields.CharField(attribute='ccn_code', readonly=True)

    # recursive field
    previous_title = fields.ForeignKey('self', 'previous_title', null=True)
    succeeding_title = fields.ForeignKey('self', 'succeeding_title', null=True)

    class Meta(ApiKeyAuthMeta):
        queryset = Journal.objects.all().filter()
        resource_name = 'journals'
        allowed_methods = [
            'get',
        ]
        filtering = {
            'is_trashed': ('exact', ),
            'eletronic_issn': ('exact', ),
            'print_issn': ('exact', ),
        }

    def build_filters(self, filters=None):
        """
        Custom filter that retrieves data by the collection's name_slug.
        """
        if filters is None:
            filters = {}

        orm_filters = super(JournalResource, self).build_filters(filters)

        if 'collection' in filters:
            journals = Journal.objects.filter(
                collections__name_slug=filters['collection'])
            orm_filters['pk__in'] = journals

        if 'pubstatus' in filters:
            # keep the previous filtering
            try:
                j = orm_filters['pk__in']
            except KeyError:
                j = Journal.objects

            statuses = filters.getlist('pubstatus')
            journals = j.filter(membership__status__in=statuses)
            orm_filters['pk__in'] = journals

        return orm_filters

    def dehydrate_missions(self, bundle):
        """
        IMPORTANT: Changed to dict on V2
            missions: {
                en: "To publish articles of clinical and experimental...",
                es: "Publicar artículos de estudios clínicos y experim...",
                pt: "Publicar artigos de estudos clínicos e experiment..."
            },
        """
        return [(mission.language.iso_code, mission.description)
                for mission in bundle.obj.missions.all()]

    def dehydrate_other_titles(self, bundle):
        """
        IMPORTANT: Changed to dict on V2
            other_titles: {
                other: "Arquivos Brasileiros de Cirurgia Digestiva",
                paralleltitle: "Brazilian Archives of Digestive Surgery"
            },
        """
        return [(title.category, title.title)
                for title in bundle.obj.other_titles.all()]

    def dehydrate_languages(self, bundle):
        return [language.iso_code for language in bundle.obj.languages.all()]

    def dehydrate_subject_categories(self, bundle):
        return [
            subject_category.term
            for subject_category in bundle.obj.subject_categories.all()
        ]

    def dehydrate_pub_status_history(self, bundle):
        return [{
            'date': event.since,
            'status': event.status
        } for event in bundle.obj.statuses.order_by('-since').all()]

    def dehydrate_study_areas(self, bundle):
        return [area.study_area for area in bundle.obj.study_areas.all()]

    def dehydrate_collections(self, bundle):
        """
        Only works with v1, without multiple collections per journal.
        IMPORTANT: This prepare function was removed from V2
        """
        try:
            return bundle.data['collections'][0]
        except IndexError:
            return ''

    def dehydrate_pub_status(self, bundle):
        """
        The version v1 of API doesnt work with multiple collections.

        To get the information about status of journal is mandatory the collection
        context, so we get this in the query string.

        IMPORTANT: the param ``collection`` is mandatory.
        """
        try:
            col = bundle.obj.collections.get()
        except MultipleObjectsReturned:
            # Get collection by query string
            query_collection = bundle.request.GET.get('collection')

            if query_collection:
                col = bundle.obj.collections.get(name_slug=query_collection)

            else:
                raise BadRequest("missing collection param")

        return bundle.obj.membership_info(col, 'status')

    def dehydrate_pub_status_reason(self, bundle):
        """
        The version v1 of API doesnt work with multiple collections.

        To get the information about status of journal is mandatory the collection
        context, so we get this in the query string.

        IMPORTANT: the param ``collection`` is mandatory.
        """
        try:
            col = bundle.obj.collections.get()
        except MultipleObjectsReturned:
            # Get collection by query string
            query_collection = bundle.request.GET.get('collection')

            if query_collection:
                col = bundle.obj.collections.get(name_slug=query_collection)

            else:
                raise BadRequest("missing collection param")

        return bundle.obj.membership_info(col, 'reason')

    def dehydrate(self, bundle):
        # garantia de compatibilidade
        bundle.data.pop('ccn_code', False)
        return bundle
コード例 #12
0
 class Nested:
     entryinfo = fields.OneToManyField('api.resources.EntryInfoResource',
                                       'entryinfo')
コード例 #13
0
ファイル: resources.py プロジェクト: rerb/stars
class SubcategorySubmissionResource(StarsApiResource):
    """
        Resource for accessing any SubcategorySubmission
    """
    subcategory = fields.ForeignKey(CREDITS_RESOURCE_PATH +
                                    'NestedSubcategoryResource',
                                    'subcategory',
                                    full=True)
    category_submission = fields.ForeignKey(SUBMISSIONS_RESOURCE_PATH +
                                            'NestedCategorySubmissionResource',
                                            'category_submission',
                                            full=True)
    credit_submissions = fields.OneToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedCreditSubmissionResource',
        'creditusersubmission_set',
        full=True)

    class Meta(StarsApiResource.Meta):
        queryset = SubcategorySubmission.objects.all()
        resource_name = 'submissions/subcategory'
        allowed_methods = ['get']
        filtering = {'category': ALL_WITH_RELATIONS}
        excludes = ['id']

    def dehydrate_points(self, bundle):
        if bundle.obj.category_submission.submissionset.reporter_status:
            return None
        else:
            return bundle.data['points']

    def get_resource_uri(self,
                         bundle_or_obj=None,
                         url_name='api_dispatch_list'):
        uri = super(SubcategorySubmissionResource,
                    self).get_resource_uri(bundle_or_obj)
        if not bundle_or_obj:
            return uri
        # default uri is
        #    submissions/subcategory/<subcategory-submission-id>,
        # but we want to use
        #    submissions/<submission-set-id>/subcategory/<subcategory-id>
        # instead.
        submissionset_id = (
            bundle_or_obj.obj.category_submission.submissionset_id)
        uri = uri.replace('submissions/',
                          'submissions/{0}/'.format(submissionset_id))
        subcategory_id = str(bundle_or_obj.obj.subcategory_id)
        return '/'.join(uri.split('/')[:-2] + [subcategory_id, ''])

    def obj_get(self, bundle, **kwargs):
        """Given the id of a Subcategory and a SubmissionSet,
        get the matching SubcategorySubmission.
        """
        submissionset = kwargs.pop('submissionset')

        kwargs['pk'] = kwargs.pop('subcatpk')
        subcategory = Subcategory.objects.get(**kwargs)

        return subcategory.subcategorysubmission_set.get(
            category_submission__submissionset=submissionset)

    def obj_get_list(self, bundle, **kwargs):
        submissionset_id = kwargs.pop('submissionset_id')
        categories_for_submissionset = CategorySubmission.objects.filter(
            submissionset=submissionset_id)
        return SubcategorySubmission.objects.filter(
            category_submission__in=categories_for_submissionset)
コード例 #14
0
class JournalResource(ModelResource):
    missions = fields.CharField(readonly=True)
    other_titles = fields.CharField(readonly=True)
    creator = fields.ForeignKey(UserResource, 'creator')
    abstract_keyword_languages = fields.CharField(readonly=True)
    languages = fields.CharField(readonly=True)
    use_license = fields.ForeignKey(UseLicenseResource,
                                    'use_license',
                                    full=True)
    sponsors = fields.ManyToManyField(SponsorResource, 'sponsor')
    collections = fields.ManyToManyField(CollectionResource, 'collections')
    issues = fields.OneToManyField(IssueResource, 'issue_set')
    sections = fields.OneToManyField(SectionResource, 'section_set')
    pub_status_history = fields.ListField(readonly=True)
    contact = fields.DictField(readonly=True)
    study_areas = fields.ListField(readonly=True)
    pub_status = fields.CharField(readonly=True)
    pub_status_reason = fields.CharField(readonly=True)

    #recursive field
    previous_title = fields.ForeignKey('self', 'previous_title', null=True)

    class Meta(ApiKeyAuthMeta):
        queryset = Journal.objects.all().filter()
        resource_name = 'journals'
        allowed_methods = [
            'get',
        ]
        filtering = {
            'is_trashed': ('exact', ),
            'eletronic_issn': ('exact', ),
            'print_issn': ('exact', ),
        }

    def build_filters(self, filters=None):
        """
        Custom filter that retrieves data by the collection's name_slug.
        """
        if filters is None:
            filters = {}

        orm_filters = super(JournalResource, self).build_filters(filters)

        if 'collection' in filters:
            journals = Journal.objects.filter(
                collections__name_slug=filters['collection'])
            orm_filters['pk__in'] = journals

        if 'pubstatus' in filters:
            # keep the previous filtering
            try:
                j = orm_filters['pk__in']
            except KeyError:
                j = Journal.objects

            statuses = filters.getlist('pubstatus')
            journals = j.filter(membership__status__in=statuses)
            orm_filters['pk__in'] = journals

        return orm_filters

    def dehydrate_missions(self, bundle):
        return [(mission.language.iso_code, mission.description)
                for mission in bundle.obj.missions.all()]

    def dehydrate_other_titles(self, bundle):
        return [(title.category, title.title)
                for title in bundle.obj.other_titles.all()]

    def dehydrate_languages(self, bundle):
        return [language.iso_code for language in bundle.obj.languages.all()]

    def dehydrate_pub_status_history(self, bundle):
        return [{
            'date': event.since,
            'status': event.status
        } for event in bundle.obj.statuses.order_by('-since').all()]

    def dehydrate_study_areas(self, bundle):
        return [area.study_area for area in bundle.obj.study_areas.all()]

    def dehydrate_collections(self, bundle):
        """Only works com v1, without multiple collections per journal.
        """
        try:
            return bundle.data['collections'][0]
        except IndexError:
            return ''

    def dehydrate_pub_status(self, bundle):
        col = bundle.obj.collections.get()
        return bundle.obj.membership_info(col, 'status')

    def dehydrate_pub_status_reason(self, bundle):
        col = bundle.obj.collections.get()
        return bundle.obj.membership_info(col, 'reason')
コード例 #15
0
ファイル: resources.py プロジェクト: Persice/persice.com
class UserResource(ModelResource):
    goals = fields.OneToManyField(
        'goals.api.resources.GoalResource',
        attribute=lambda bundle: bundle.obj.goal_set.all(),
        full=True,
        null=True)
    offers = fields.OneToManyField(
        'goals.api.resources.OfferResource',
        attribute=lambda bundle: bundle.obj.offer_set.all(),
        full=True,
        null=True)
    interests = fields.OneToManyField(
        'interests.api.resources.'
        'InterestResource',
        attribute=lambda bundle: bundle.obj.interest_set.all(),
        full=True,
        null=True)

    onboardingflow = fields.OneToOneField(OnBoardingFlowResource,
                                          'onboardingflow',
                                          full=True,
                                          null=True)
    image = fields.FileField(attribute='image', null=True, readonly=True)

    class Meta:
        queryset = FacebookCustomUserActive.objects.all()
        resource_name = 'auth/user'
        fields = [
            'username', 'first_name', 'last_name', 'last_login', 'about_me',
            'facebook_id', 'id', 'date_of_birth', 'facebook_profile_url',
            'gender', 'image', 'email', 'date_joined'
        ]
        filtering = {'facebook_id': ALL}
        authentication = JSONWebTokenAuthentication()
        authorization = Authorization()

    def dehydrate(self, bundle):
        bundle.data['distance'] = calculate_distance(bundle.request.user.id,
                                                     bundle.obj.id)

        bundle.data['mutual_friends'] = \
            len(Friend.objects.mutual_friends(bundle.request.user.id,
                                              bundle.obj.id))

        bundle.data['age'] = calculate_age(bundle.data['date_of_birth'])

        # TODO chane user_id to url from user_id
        bundle.data['twitter_provider'], bundle.data['linkedin_provider'], \
            bundle.data['twitter_username'], bundle.data['linkedin_first_name'] = \
            social_extra_data(bundle.request.user.id)

        if bundle.obj.id != bundle.request.user.id:
            bundle.data['match_score'] = MatchEngine.objects. \
                count_common_goals_and_offers(bundle.obj.id,
                                              bundle.request.user.id)
        else:
            bundle.data['match_score'] = 0

        bundle.data['position'] = get_current_position(bundle.obj)
        bundle.data['lives_in'] = get_lives_in(bundle.obj)
        bundle.data['religious_views'] = get_religious_views(
            bundle.request.user.id)
        bundle.data['political_views'] = get_political_views(
            bundle.request.user.id)
        bundle.data['image'] = FacebookPhoto.objects.profile_photo(
            bundle.obj.id)
        return bundle

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/search%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_search'),
                name="api_get_search"),
        ]

    def get_search(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        # Do the query.
        query = request.GET.get('q', '')
        sqs = SearchQuerySet().models(FacebookCustomUserActive).load_all(). \
            filter(SQ(first_name=query) |
                   SQ(last_name=query) |
                   SQ(goals=query) |
                   SQ(offers=query) |
                   SQ(likes=query) |
                   SQ(interests=query)).\
            exclude(id=request.user.id)
        paginator = Paginator(sqs, 10)

        try:
            page = paginator.page(int(request.GET.get('page', 1)))
        except InvalidPage:
            raise Http404("Sorry, no results on that page.")

        objects = []

        for result in page.object_list:
            bundle = self.build_bundle(obj=result.object, request=request)
            bundle = self.full_dehydrate(bundle)
            objects.append(bundle)

        object_list = {
            'objects': objects,
        }

        self.log_throttled_access(request)
        return self.create_response(request, object_list)
コード例 #16
0
ファイル: resources.py プロジェクト: rerb/stars
class CreditSubmissionResource(StarsApiResource):
    """
        Resource for accessing any CreditSubmission
    """
    credit = fields.ForeignKey(CREDITS_RESOURCE_PATH + 'NestedCreditResource',
                               'credit',
                               full=True)
    subcategory_submission = fields.ForeignKey(
        SUBMISSIONS_RESOURCE_PATH + 'NestedSubcategorySubmissionResource',
        'subcategory_submission',
        full=True)
    boolean_submissions = fields.OneToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedBooleanSubmissionResource',
        'booleansubmission_set',
        full=True)
    choice_submissions = fields.OneToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedChoiceSubmissionResource',
        'choicesubmission_set',
        full=True)
    date_submissions = fields.OneToManyField(SUBMISSIONS_RESOURCE_PATH +
                                             'NestedDateSubmissionResource',
                                             'datesubmission_set',
                                             full=True)
    longtext_submissions = fields.OneToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedLongTextSubmissionResource',
        'longtextsubmission_set',
        full=True)
    multichoice_submissions = fields.OneToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedMultiChoiceSubmissionResource',
        'multichoicesubmission_set',
        full=True)
    numeric_submissions = fields.OneToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedNumericSubmissionResource',
        'numericsubmission_set',
        full=True)
    text_submissions = fields.OneToManyField(SUBMISSIONS_RESOURCE_PATH +
                                             'NestedTextSubmissionResource',
                                             'textsubmission_set',
                                             full=True)
    upload_submissions = fields.OneToManyField(
        SUBMISSIONS_RESOURCE_PATH + 'NestedUploadSubmissionResource',
        'uploadsubmission_set',
        full=True)
    url_submissions = fields.OneToManyField(SUBMISSIONS_RESOURCE_PATH +
                                            'NestedURLSubmissionResource',
                                            'urlsubmission_set',
                                            full=True)

    class Meta(StarsApiResource.Meta):
        queryset = CreditUserSubmission.objects.all()
        resource_name = 'submissions/credit'
        allowed_methods = ['get']
        # exclude submission_notes  becauses it raises
        # "'ascii' codec can't decode byte ... in position ...: ordinal not
        # in range(128)"
        excludes = [
            'last_updated', 'internal_notes', 'responsible_party_confirm',
            'submission_notes', 'id'
        ]

    def dehydrate_title(self, bundle):
        return bundle.obj.credit.title

    def dehydrate(self, bundle):
        bundle.data['title'] = self.dehydrate_title(bundle)

        if bundle.obj.subcategory_submission.category_submission.submissionset.reporter_status:
            bundle.data['assessed_points'] = None

        # combine all the fields into one list
        field_list = []
        field_types = [
            "boolean_submissions", "choice_submissions", "date_submissions",
            "longtext_submissions", "multichoice_submissions",
            "numeric_submissions", "text_submissions", "upload_submissions",
            "url_submissions"
        ]

        for ft in field_types:
            for f in bundle.data[ft]:
                field_list.append(f)
            del bundle.data[ft]

        # only show the fields if they're published with this credit
        if submission_rules.publish_credit_data(bundle.obj):
            bundle.data['documentation_fields'] = field_list

        return bundle

    def get_resource_uri(self,
                         bundle_or_obj=None,
                         url_name='api_dispatch_list'):
        uri = super(CreditSubmissionResource,
                    self).get_resource_uri(bundle_or_obj)
        if not bundle_or_obj:
            return uri
        # default uri is
        #    submissions/credit/<credit-submission-id>,
        # but we want to use
        #    submissions/<submission-set-id>/credit/<credit-id>
        # instead.
        credit_user_submission = bundle_or_obj.obj.creditusersubmission
        subcategory_submission = credit_user_submission.subcategory_submission
        category_submission = subcategory_submission.category_submission
        submissionset_id = category_submission.submissionset.id
        uri = uri.replace('submissions/',
                          'submissions/{0}/'.format(submissionset_id))
        credit_id = str(bundle_or_obj.obj.credit_id)
        return '/'.join(uri.split('/')[:-2] + [credit_id, ''])

    def obj_get(self, bundle, **kwargs):
        """Given the id of a Credit and a SubmissionSet, get the matching
        CreditSubmission.
        """
        # TODO: BEN - what about this crazy get()?
        credit = Credit.objects.get(pk=kwargs['credpk'])
        return credit.creditsubmission_set.get(
            creditusersubmission__subcategory_submission__category_submission__submissionset
            =kwargs['submissionset']).creditusersubmission

    def obj_get_list(self, bundle, **kwargs):
        submissionset_id = kwargs.pop('submissionset_id')
        categories_for_submissionset = CategorySubmission.objects.filter(
            submissionset=submissionset_id)
        subcategories_for_submissionset = (
            SubcategorySubmission.objects.filter(
                category_submission__in=categories_for_submissionset))
        return CreditUserSubmission.objects.filter(
            subcategory_submission__in=subcategories_for_submissionset)
コード例 #17
0
class JournalResource(ModelResource):
    missions = fields.CharField(readonly=True)
    other_titles = fields.CharField(readonly=True)
    abstract_keyword_languages = fields.CharField(readonly=True)
    languages = fields.CharField(readonly=True)
    pub_status_history = fields.ListField(readonly=True)
    contact = fields.DictField(readonly=True)
    study_areas = fields.ListField(readonly=True)
    pub_status = fields.CharField(readonly=True)
    pub_status_reason = fields.CharField(readonly=True)
    national_code = fields.CharField(attribute='ccn_code', readonly=True)

    # Relation fields
    creator = fields.ForeignKey(UserResource, 'creator')
    use_license = fields.ForeignKey(UseLicenseResource,
                                    'use_license',
                                    full=True)
    sponsors = fields.ManyToManyField(SponsorResource, 'sponsor')
    collections = fields.ManyToManyField(CollectionResource, 'collections')
    issues = fields.OneToManyField(IssueResource, 'issue_set')
    sections = fields.OneToManyField(SectionResource, 'section_set')
    subject_categories = fields.ManyToManyField(SubjectCategoryResource,
                                                'subject_categories',
                                                readonly=True)

    # Recursive field
    previous_title = fields.ForeignKey('self', 'previous_title', null=True)
    succeeding_title = fields.ForeignKey('self', 'succeeding_title', null=True)

    class Meta(ApiKeyAuthMeta):
        queryset = models.Journal.objects.all()
        resource_name = 'journals'
        allowed_methods = [
            'get',
        ]
        filtering = {
            'is_trashed': ('exact', ),
            'eletronic_issn': ('exact', ),
            'print_issn': ('exact', ),
        }

    def build_filters(self, filters=None):
        """
        Custom filter that retrieves data filter by collection and pubstatus.
        """
        if filters is None:
            filters = {}

        query_filters = {}

        orm_filters = super(JournalResource, self).build_filters(filters)

        if 'collection' in filters:
            query_filters['collections__name_slug'] = filters['collection']

        if 'pubstatus' in filters:
            query_filters['membership__status__in'] = filters.getlist(
                'pubstatus')

        journals = models.Journal.objects.filter(**query_filters)

        orm_filters['pk__in'] = journals

        return orm_filters

    def dehydrate_missions(self, bundle):
        return {
            mission.language.iso_code: mission.description
            for mission in bundle.obj.missions.all()
        }

    def dehydrate_other_titles(self, bundle):
        return {
            title.category: title.title
            for title in bundle.obj.other_titles.all()
        }

    def dehydrate_languages(self, bundle):
        return [language.iso_code for language in bundle.obj.languages.all()]

    def dehydrate_pub_status_history(self, bundle):
        return [{
            'date': event.since,
            'status': event.status
        } for event in bundle.obj.statuses.order_by('-since').all()]

    def dehydrate_study_areas(self, bundle):
        return [area.study_area for area in bundle.obj.study_areas.all()]

    def dehydrate_pub_status(self, bundle):
        return {
            col.name: bundle.obj.membership_info(col, 'status')
            for col in bundle.obj.collections.all()
        }

    def dehydrate_pub_status_reason(self, bundle):
        return {
            col.name: bundle.obj.membership_info(col, 'reason')
            for col in bundle.obj.collections.all()
        }

    def dehydrate_collections(self, bundle):
        return [col.name for col in bundle.obj.collections.all()]

    def dehydrate_subject_categories(self, bundle):
        return [
            subject_category.term
            for subject_category in bundle.obj.subject_categories.all()
        ]

    def dehydrate(self, bundle):
        # garantia de compatibilidade
        bundle.data.pop('ccn_code', False)
        return bundle