Beispiel #1
0
class UserProfileResource(CorsResource):
    user = fields.ForeignKey(UserResource, 'user', full=True)
    identifier = fields.ManyToManyField(UniqueIdentifierResource,'identifier',full=True, null=True,blank=True)
    default_pocket = fields.ForeignKey('website.api.resources.PocketResource', 'default_pocket', full=True)
    pockets = fields.ManyToManyField('website.api.resources.PocketResource', 'pockets',full=True, null=True, blank=True)
    class Meta:
        # For authentication, allow both basic and api key so that the key
        # can be grabbed, if needed.
        authentication = MultiAuthentication(
            InlineBasicAuthentication(),
            BasicAuthentication(),
            ApiKeyAuthentication(),TokenAuthentication())
        authorization = UserAuthorization()
        always_return_data = True
        allowed_methods = ['get', 'patch','put' ,'options']
        detail_allowed_methods = ['get', 'put']
        queryset = UserProfile.objects.all()
        resource_name = 'profile'
        filtering = {'user':ALL_WITH_RELATIONS, 'identifier':ALL_WITH_RELATIONS}
        serializer = Serializer(formats=['json','jsonp'])
 
    def authorized_read_list(self, object_list, bundle):
        return object_list.filter(user__username=bundle.request.user.username).select_related()
 
    ## Since there is only one user profile object, call get_detail instead
    def get_list(self, request, **kwargs):
        kwargs["user"] = request.user
        return super(UserProfileResource, self).get_detail(request, **kwargs)
Beispiel #2
0
class AudioSegmentResource(NestedResource):
    name = fields.CharField('name')
    beginning = fields.FloatField('beginning')
    end = fields.FloatField('end')
    creator = fields.ForeignKey(UserResource, 'creator')
    audioFile = fields.ForeignKey(AudioFileResource, 'audioFile')
    tags = fields.ManyToManyField(TagResource, 'tags', null=True)
    collection = fields.ForeignKey(CollectionResource, 'collection')
    events = fields.ManyToManyField('concertapp.event.api.EventResource',
                                    'events',
                                    null=True)

    class Meta(NestedResource.Meta):
        authentication = DjangoAuthentication()
        authorization = AudioSegmentAuthorization()
        queryset = AudioSegment.objects.all()

        filtering = {"tags": ALL}

        nested = 'tags'

    def create_nested_event(self, obj, nested_obj, request):
        AudioSegmentTaggedEvent.objects.create(collection=obj.collection,
                                               audioSegment=obj,
                                               tag=nested_obj,
                                               user=request.user)
        return
Beispiel #3
0
class RestaurantResource(ModelResource):
    restauranttype = fields.ManyToManyField(RestaurantTypeResource,
                                            'restauranttype_set',
                                            full=True,
                                            full_detail=True)
    cuisine = fields.ManyToManyField(CuisineResource,
                                     'cuisine_set',
                                     full=True,
                                     full_detail=True)
    food = fields.ManyToManyField(FoodResource,
                                  'food_set',
                                  full=True,
                                  full_detail=True)
    events = fields.ManyToManyField('restauranthub.api.EventsResource',
                                    'events_set',
                                    related_name='restaurant')
    offers = fields.ManyToManyField('restauranthub.api.OffersResource',
                                    'offers_set',
                                    related_name='restaurant')

    class Meta:
        queryset = Restaurant.objects.all()
        resource_name = 'restaurant'
        filtering = {'restaurant_name': ALL}
        # authentication = BasicAuthentication()
        authentication = ApiKeyAuthentication()
Beispiel #4
0
class MovieResource(ModelResource):
    happiness = FixedFloatField(attribute="happs")
    reference = fields.CharField("filename")
    ignorewords = fields.CharField("ignorewords")
    director = fields.ManyToManyField('hedonometer.api.DirectorResource',
                                      'director',
                                      full=True)
    writer = fields.ManyToManyField('hedonometer.api.DirectorResource',
                                    'writer',
                                    full=True)
    actor = fields.ManyToManyField('hedonometer.api.DirectorResource',
                                   'actor',
                                   full=True)

    class Meta:
        queryset = Movie.objects.all().exclude(exclude=True)
        resource_name = "movies"
        # excludes = ["happs","id","filename",]
        include_resource_uri = False
        max_limit = None
        limit = 50000
        filtering = {
            "title": ALL_WITH_RELATIONS,
            "id": ALL,
            "length": ALL_WITH_RELATIONS,
            "annotation": ALL,
        }
Beispiel #5
0
class SectorResource(ModelResource):
    name = fields.CharField("name")
    stocks = fields.ManyToManyField("stock.api.StockResource",
                                    "stocks",
                                    null=True)
    stocks_detail = fields.ManyToManyField(
        "stock.api.StockResource",
        "stocks",
        null=True,
        full=True,
        readonly=True,
        use_in="detail",
    )
    stocks_property = fields.ListField("stocks_property",
                                       null=True,
                                       readonly=True)

    class Meta:
        queryset = MySector.objects.all()
        resource_name = "sectors"
        filtering = {"name": ALL}
        authorization = Authorization()

    def obj_update(self, bundle, **kwargs):
        super().obj_update(bundle)

        sector = bundle.obj

        for stock in sector.stocks.all():
            # kick off updates
            batch_update_helper(sector.name, stock.symbol)
Beispiel #6
0
class CandidateResource(ModelResource):
    personal_data = fields.ManyToManyField(PersonalDataResource,
                                           'personal_data',
                                           null=True,
                                           full=True)
    links = fields.ToManyField(LinkResource, 'link_set', full=True)
    background = fields.ManyToManyField(BackgroundResource,
                                        'background',
                                        full=True)

    class Meta:
        queryset = Candidate.objects.all()
        resource_name = 'candidate'
        authentication = ApiKeyAuthentication()

    def authorized_read_list(self, object_list, bundle):
        return object_list.filter(election__owner=bundle.request.user)

    def dehydrate(self, bundle):
        candidate = bundle.obj
        categories = bundle.obj.election.category_set.all()
        bundle.data["categories"] = []

        for category in categories:
            questions_array = []
            for question in category.question_set.all():
                answers = Answer.objects.filter(question=question).filter(
                    candidate=candidate)
                the_answer = None
                if len(answers) == 1:
                    the_answer = {
                        "id": answers[0].id,
                        "caption": answers[0].caption
                    }
                questions_array.append({
                    "id": question.id,
                    "answer": the_answer,
                    "question": question.question
                })

            category_dict = {
                "id": category.id,
                "name": category.name,
                "questions": questions_array
            }

            bundle.data["categories"].append(category_dict)

        for pdata in bundle.data['personal_data']:
            personal_data_candidate = PersonalDataCandidate.objects.get(
                candidate=bundle.obj, personal_data=pdata.obj)
            pdata.data['value'] = personal_data_candidate.value
            del pdata.data['resource_uri']

        for data in bundle.data['background']:
            background_candidate = BackgroundCandidate.objects.get(
                candidate=bundle.obj, background=data.obj)
            data.data['value'] = background_candidate.value

        return bundle
Beispiel #7
0
class NakopitelnayaVedomostResource(ModelResource):
    regforms = fields.ManyToManyField(TractorRegFormResource,
                                      'regforms',
                                      full=True,
                                      null=True)
    outfits = fields.ManyToManyField(OutfitResource,
                                     'outfits',
                                     full=True,
                                     null=True)
    author = fields.ForeignKey(UserResource, 'author', full=True)
    station = fields.ForeignKey(StationResource, 'station', full=True)
    event = fields.ForeignKey(OutfitEventResource,
                              'event',
                              full=True,
                              null=True)
    departament_full = fields.ApiField('get_departament_display')
    calcs = fields.ApiField('get_calcs_counter')

    class Meta:
        queryset = models.NakopitelnayaVedomost.objects.all()
        resource_name = 'nakopitelnie_vedomosti'
        list_allowed_methods = ['get', 'post', 'put', 'delete']
        detail_allowed_methods = ['get', 'post', 'put', 'delete']
        collection_name = 'nakopitelnie_vedomosti'
        authorization = Authorization()
        authentication = MultiAuthentication(SessionAuthentication(),
                                             ApiKeyAuthentication())
        filtering = {
            'id': ALL,
            'date': ALL,
            'created_date': ALL,
            'author': ALL_WITH_RELATIONS,
            'station': ALL_WITH_RELATIONS,
            'event': ALL_WITH_RELATIONS,
            'departament': ALL,
        }

    def post_list(self, request, **kwargs):
        data = json.loads(request.body.decode('utf-8'))
        data['author'] = request.user.pk
        errors = []
        calcs_list = []
        form = prd_forms.NakopitelnayaVedomostForm(data)
        if form.is_valid():
            vedomost = form.save()
            for of in vedomost.outfits.all():
                of.conducted = True
                of.save()
            for rf in vedomost.regforms.all():
                rf.conducted = True
                rf.save()
        else:
            errors.append(form.errors)
        if not len(errors):
            return self.create_response(request, {'id': vedomost.pk})
        else:
            return self.error_response(request, errors)
Beispiel #8
0
class ForumResource(ModelResource):
    moderators = fields.ManyToManyField(UserResource, 'moderators', full=True)
    members    = fields.ManyToManyField(UserResource, 'members', full=True)

    class Meta:
        resource_name = 'forum'
        queryset = Forum.objects.all()
        authorization = Authorization()
        always_return_data = True
Beispiel #9
0
class GraphResource(CustomSaveHookResource):
    """
    NOTE: can't commit dependencies if concepts are not already present in graph'
    """
    concepts = fields.ManyToManyField(ConceptResource, 'concepts', null=True)
    dependencies = fields.ManyToManyField(DependencyResource,
                                          'dependencies',
                                          null=True)

    def dehydrate(self, bundle):
        """
        Dehydrate with full=true specified in the url
        """
        show_full = bundle.request.GET.get('full', "false").lower() == "true"
        # awkward hack to allow the full parameter to be specified in the url
        if show_full:
            c_old_full = self.concepts.full
            self.concepts.full = True
            bundle.data['concepts'] = self.concepts.dehydrate(bundle)
            self.concepts.full = c_old_full
            d_old_full = self.dependencies.full
            self.dependencies.full = True
            bundle.data['dependencies'] = self.dependencies.dehydrate(bundle)
            self.dependencies.full = d_old_full

        return bundle

    def alter_deserialized_detail_data(self, request, data):
        # create the graph if it does not exist and associate the user with the graph
        id_to_concept = {}
        if data["concepts"]:
            for concept in data["concepts"]:
                if type(
                        concept
                ) != dict:  # if it's a Bundle, this function has already been called
                    continue
                concept = normalize_concept(concept)
                id_to_concept[concept["id"]] = concept

        return data

    def post_save_hook(self, bundle):
        # FIXME we're assuming a user is logged in
        gsettings, gsnew = GraphSettings.objects.get_or_create(
            graph=bundle.obj)
        uprof, created = Profile.objects.get_or_create(
            pk=bundle.request.user.pk)

        # TODO add check that the edit actally made a difference
        gsettings.edited_by.add(uprof)
        return bundle

    class Meta(BaseResource.Meta):
        """ GraphResource Meta """
        queryset = Graph.objects.all()
        resource_name = 'graph'
Beispiel #10
0
class FestivalResource(ModelResource):
    picture = fields.ForeignKey(SelectPictureResource, 'picture', null=True)
    programmer = fields.ForeignKey(SelectProgrammerResource, 'programmer')
    approval = fields.ForeignKey(SelectApprovalResource, 'approval', null=True)
    films = fields.ManyToManyField(FilmResource, 'films')
    gigs = fields.ManyToManyField(GigResource, 'events')
    events = fields.ManyToManyField(EventResource, 'events')

    class Meta:
        queryset = Festival.objects.all()
        authentication = SessionAuthentication()
        authorization = Authorization()
Beispiel #11
0
class GenericResourceResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')
    creator = fields.ForeignKey(UserResource, 'creator')
    edit_users = fields.OneToManyField(UserResource,
                                       'edit_users',
                                       related_name='can_edit',
                                       blank=True)
    view_users = fields.OneToManyField(UserResource,
                                       'edit_users',
                                       related_name='can_edit',
                                       blank=True)
    edit_groups = fields.OneToManyField(GroupResource,
                                        'edit_users',
                                        related_name='can_edit',
                                        blank=True)
    view_groups = fields.OneToManyField(GroupResource,
                                        'edit_users',
                                        related_name='can_edit',
                                        blank=True)
    owners = fields.OneToManyField(UserResource,
                                   'owners',
                                   related_name='owner_of',
                                   blank=True)
    dublin_metadata = fields.ManyToManyField("hs_core.api.DublinCoreResource",
                                             'dublin_metadata',
                                             related_name='content_object',
                                             full=True)
    files = fields.ManyToManyField('hs_core.api.ResourceFileResource',
                                   'files',
                                   related_name='content_object',
                                   full=True)

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<short_id>[\w\d_.-]+)/$" %
                self._meta.resource_name,
                self.wrap_view('dispatch_detail'),
                name="api_dispatch_detail"),
        ]

    class Meta:
        always_return_data = True
        queryset = GenericResource.objects.all()
        resource_name = 'genericresource'
        filtering = {
            'id': 'exact',
        }
        authentication = MultiAuthentication(BasicAuthentication(),
                                             ApiKeyAuthentication(),
                                             SessionAuthentication())
        #authorization = HydroshareAuthorization()
        authorization = Authorization()
Beispiel #12
0
class IssueResource(ModelResource):
    class Meta:
        # List of all objects to be displayed in base URL
        queryset = Issue.objects.all()
        # Resource name mapped to URL
        resource_name = 'issue'
        # Fields to be excluded from data returned to client

    assigned_to = fields.ManyToManyField(PersonResource,
                                         'assigned_to',
                                         full=False)
    reporter = fields.ToOneField(PersonResource, 'reporter', full=False)
    rel_commits = fields.ManyToManyField(CommitResource,
                                         'rel_commits',
                                         full=False)
Beispiel #13
0
class MemberResource(ModelResource):
    current_party = fields.ForeignKey(PartyResource, 'current_party', null=True, blank=True)
    if hasattr(MEMBER_MODEL, 'parties'):
        parties = fields.ManyToManyField(PartyResource, 'parties')
    main_feed = fields.ToOneField(Facebook_FeedResource, attribute='main_feed', null=True)

    class Meta:
        queryset = MEMBER_MODEL.objects.all()
        resource_name = 'member'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']

    def dehydrate_main_feed(self, bundle):
        persona = bundle.obj.facebook_persona
        if persona is not None:
            return get_resource_uri(persona.get_main_feed, self.main_feed)

        return None

    def dehydrate(self, bundle):
        bundle.data['kikar_link'] = 'http://www.kikar.org/member/' + str(bundle.obj.id)
        persona = bundle.obj.facebook_persona

        if persona is not None:
            bundle.data['facebook_link'] = persona.get_main_feed.link
        else:
            bundle.data['feed_url'] = None
        return bundle
Beispiel #14
0
class ForestArrivalReportResource(ModelResource):
    author = fields.ForeignKey(UserResource, 'author', full=True)
    station = fields.ForeignKey(StationResource, 'station', full=True)
    postings = fields.ManyToManyField(OutfitPostingResource,
                                      'postings',
                                      full=True,
                                      null=True)

    class Meta:
        queryset = models.ForestArrivalReport.objects.all()
        resource_name = 'forest-arrival-reports'
        list_allowed_methods = ['get', 'post', 'put', 'delete']
        detail_allowed_methods = ['get', 'post', 'put', 'delete']
        collection_name = 'reports'
        authorization = Authorization()
        authentication = MultiAuthentication(SessionAuthentication(),
                                             ApiKeyAuthentication())
        filtering = {
            'station': ALL_WITH_RELATIONS,
            'postings': ALL_WITH_RELATIONS,
            'author': ALL_WITH_RELATIONS,
            'date': ALL,
        }

    def post_list(self, request, **kwargs):
        data = json.loads(request.body.decode('utf-8'))
        data['author'] = request.user.pk
        form = prd_forms.ForestArrivalReportForm(data)
        if form.is_valid():
            report = form.save()
            return self.create_response(request, {'id': report.pk})
        else:
            return self.error_response(request, form.errors)
Beispiel #15
0
class AccountResource(BaseModelResource):

    users = fields.ManyToManyField('api.partner_v1.resources.UserResource', 'users')

    class Meta(BaseMeta):
        queryset = Account.objects.all()
        fields = ['resource_uri']
Beispiel #16
0
class FindingResource(BaseModelResource):
    reporter = fields.ForeignKey(UserResource, 'reporter', null=False)
    test = fields.ForeignKey(TestResource, 'test', null=False)
    risk_acceptance = fields.ManyToManyField(RiskAcceptanceResource,
                                             'risk_acceptance',
                                             null=True)
    product = fields.ForeignKey(ProductResource,
                                'test__engagement__product',
                                full=False,
                                null=False)
    engagement = fields.ForeignKey(EngagementResource,
                                   'test__engagement',
                                   full=False,
                                   null=False)

    class Meta:
        resource_name = 'findings'
        queryset = Finding.objects.select_related("test")
        # deleting of findings is not allowed via API.
        # Admin interface can be used for this.
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'post', 'put']
        include_resource_uri = True
        filtering = {
            'id': ALL,
            'title': ALL,
            'date': ALL,
            'severity': ALL,
            'description': ALL,
            'mitigated': ALL,
            'endpoint': ALL,
            'test': ALL_WITH_RELATIONS,
            'active': ALL,
            'verified': ALL,
            'false_p': ALL,
            'reporter': ALL,
            'url': ALL,
            'out_of_scope': ALL,
            'duplicate': ALL,
            'risk_acceptance': ALL,
            'engagement': ALL_WITH_RELATIONS,
            'product': ALL_WITH_RELATIONS
        }
        authentication = DojoApiKeyAuthentication()
        authorization = DjangoAuthorization()
        serializer = Serializer(formats=['json'])

        @property
        def validation(self):
            return ModelFormValidation(form_class=FindingForm,
                                       resource=FindingResource)

    def dehydrate(self, bundle):
        engagement = Engagement.objects.select_related('product'). \
            filter(test__finding__id=bundle.obj.id)
        bundle.data[
            'engagement'] = "/api/v1/engagements/%s/" % engagement[0].id
        bundle.data['product'] = \
            "/api/v1/products/%s/" % engagement[0].product.id
        return bundle
Beispiel #17
0
class ContestResource(ModelResource):
    company = fields.ForeignKey(CompanyResource, 'company')
    contestant  = fields.ManyToManyField(UserResource, 'contestant', full=True)
    contest_updates = fields.ToManyField(ProjectUpdateResource, 'contest_updates', null=True, full=True)
    class Meta:
        queryset = Contest.objects.all()
        resource = 'contest'
class BindingSiteResource(ChemblModelResource):

    site_components = fields.ManyToManyField(
        'chembl_webservices.resources.binding_site.SiteComponentsResource',
        'sitecomponents_set',
        full=True,
        null=True,
        blank=True)

    class Meta(ChemblResourceMeta):
        prefetch_related = [
            Prefetch('sitecomponents_set'),
            Prefetch('sitecomponents_set__domain'),
            Prefetch('sitecomponents_set__component',
                     queryset=ComponentSequences.objects.only('pk')),
        ]
        queryset = BindingSites.objects.all()
        resource_name = 'binding_site'
        collection_name = 'binding_sites'
        serializer = ChEMBLApiSerializer(resource_name, {
            collection_name: resource_name,
            'site_components': 'site_component'
        })
        filtering = {
            'site_id': NUMBER_FILTERS,
            'site_name': CHAR_FILTERS,
            'site_components': ALL_WITH_RELATIONS,
        }
        ordering = filtering.keys()
Beispiel #19
0
class ExperimentResource(ModelResource):
    sample_set = fields.ManyToManyField('analyze.api.SampleResource',
                                        'sample_set')

    class Meta:
        queryset = Experiment.objects.all()
        allowed_methods = ['get']
        filtering = {
            'signature': ('exact', ),  # See apply_filters().
        }

    # Implementation of "signature" filter, which allows the API to get
    # the experiements that are related to a given signature.  According
    # to the database schema, "Signature" model has many-to-many
    # relationship with "Sample" model through "Activity" model; and
    # "Sample" model has (implicit) many-to-many relationship with
    # "Experiment" model through the "experiments" field in "Sample".
    def apply_filters(self, request, applicable_filters):
        object_list = super(ExperimentResource,
                            self).apply_filters(request, applicable_filters)
        signature = request.GET.get('signature', None)
        if signature:
            # Catch ValueError exception that may be raised by int() below,
            # and raise a customized BadRequest exception with more details.
            try:
                sig_id = int(signature)
            except ValueError:
                raise BadRequest("Invalid signature ID: %s" % signature)

            samples = Activity.objects.filter(
                signature=sig_id).values('sample')
            experiments = Sample.objects.filter(
                pk__in=samples).values('experiments').distinct()
            object_list = object_list.filter(pk__in=experiments)
        return object_list
Beispiel #20
0
class ContactResource(ModelResource):

    represents = fields.ForeignKey(SupplierResource, 'represents')
    label = fields.ManyToManyField(ContactLabelResource, 'label')

    class Meta:
        resource_name = 'contacts'
        queryset = Contact.objects.all()
        filtering = {
            'id': ALL,
            'name': ALL,
            'address1': ALL,
            'address2': ALL,
            'address3': ALL,
            'city': ALL,
            'state': ALL,
            'zipcode': ALL,
            'country': ALL,
            'email': ALL,
            'work_phone': ALL,
            'cell_phone': ALL,
            'fax': ALL,
            'represents': ALL_WITH_RELATIONS,
            'label': ALL_WITH_RELATIONS,
        }
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()
        allowed_methods = ['get', ]
        always_return_data = True
Beispiel #21
0
class BankDepositLeadResource(CorsResource):
    pocket = fields.ForeignKey('website.api.resources.PocketResource', 'pocket', full=True)
    identifiers = fields.ManyToManyField('website.api.resources.UniqueIdentifierResource', 'identifiers', full=True,
                                         null=True)

    class Meta:
        authentication = MultiAuthentication(
            InlineBasicAuthentication(),
            BasicAuthentication(),
            ApiKeyAuthentication(),TokenAuthentication())
        authorization = Authorization()
        always_return_data = True
        allowed_methods = ['get','post' ]
        queryset = BankDepositLead.objects.all()
        resource_name = 'bank_deposits'
        serializer = Serializer(formats=['json'])
        exclude = []

    def hydrate(self, bundle):
        REQUIRED_FIELDS = ["pocket","reference","amount"]
        for field in REQUIRED_FIELDS:
            if field not in bundle.data:
                raise CustomBadRequest(
                    code="missing_key",
                    message="Must provide {missing_key} when creating a Bank deposit."
                        .format(missing_key=field))
Beispiel #22
0
class TransactionResource(CorsResource):
    identifiers = fields.ManyToManyField('website.api.resources.UniqueIdentifierResource', 'identifiers', full=True)
    pocket = fields.ForeignKey('website.api.resources.PocketResource', 'pocket', full=True,null=True)

    class Meta:
        authentication = MultiAuthentication(
            InlineBasicAuthentication(),
            BasicAuthentication(),
            ApiKeyAuthentication(), TokenAuthentication())
        authorization = PocketAuthorization()
        always_return_data = True
        allowed_methods = ['get']
        queryset = Transaction.objects.all()
        resource_name = 'transactions'
        serializer = Serializer(formats=['json'])
        exclude = []
        filtering = {'pocket':ALL_WITH_RELATIONS}
        ordering = ['datetime']

    def dehydrate(self, bundle):
        bundle.data['description'] = []
        for tag in bundle.obj.identifiers.all():
            bundle.data['description'].append(tag.value)
        return bundle

    def hydrate(self, bundle):
        REQUIRED_FIELDS = ["pocket","amount","debit"]
        for field in REQUIRED_FIELDS:
            if field not in bundle.data:
                raise CustomBadRequest(
                    code="missing_key",
                    message="Must provide {missing_key} when creating a Transaction."
                        .format(missing_key=field))
Beispiel #23
0
class ActivityResource(BaseResource):
    # page,count -> send order by descding date
    images = fields.ManyToManyField(ImageSpecResource,
                                    'images',
                                    null=True,
                                    full=True)
    #comments = fields.ToManyField('website.api.CommentResource', 'comment_activity')
    partner = fields.ForeignKey(PartnerResource, 'partner', null=True)
    farmer = fields.ForeignKey(PersonResource, 'farmer', null=True)
    video = fields.ForeignKey(VideoResource, 'video', null=True)
    collection = fields.ForeignKey(CollectionResource,
                                   'collection',
                                   null=True,
                                   full=True)

    def dehydrate_avatarURL(self, bundle):
        if bundle.obj.partner:
            return bundle.obj.partner.logoURL.url
        return bundle.obj.avatarURL

    def dehydrate_date(self, bundle):
        return bundle.obj.date.strftime('%b %d, %Y')

    class Meta:
        queryset = Activity.objects.all().order_by('-date')
        resource_name = 'activity'
        filtering = {
            'farmer': ALL_WITH_RELATIONS,
            'partner': ALL_WITH_RELATIONS,
            'newsFeed': 'exact',
        }
class CustomNoteResource(ModelResource):
    author = fields.ForeignKey(UserResource, 'author')
    subjects = fields.ManyToManyField(SubjectResource, 'subjects')

    class Meta:
        resource_name = 'notes'
        queryset = Note.objects.all()
Beispiel #25
0
class ProductResource(BaseResource):
    parents = fields.ManyToManyField('productstatus.core.api.ProductResource',
                                     'parents',
                                     null=True)
    projection = fields.ForeignKey('productstatus.core.api.ProjectionResource',
                                   'projection',
                                   null=True)
    source = fields.ForeignKey('productstatus.core.api.InstitutionResource',
                               'source',
                               null=True)
    contact = fields.ForeignKey('productstatus.core.api.PersonResource',
                                'contact')
    institution = fields.ForeignKey(
        'productstatus.core.api.InstitutionResource', 'institution')
    license = fields.ForeignKey('productstatus.core.api.LicenseResource',
                                'license')

    class Meta(BaseMeta):
        queryset = productstatus.core.models.Product.objects.all()
        filtering = {
            'id': resources.ALL,
            'parents': resources.ALL,
            'name': ['exact'],
            'slug': ['exact'],
            'wdb_data_provider': ['exact'],
            'source': resources.ALL_WITH_RELATIONS,
            'source_key': ['exact'],
        }
Beispiel #26
0
class ExperimentResource(ModelResource):
    sample_set = fields.ManyToManyField('analyze.api.SampleResource',
                                        'sample_set')

    class Meta:
        queryset = Experiment.objects.all()
        allowed_methods = ['get']
Beispiel #27
0
class StationResource(ModelResource):
    organization = fields.ForeignKey(OrganizationResource,
                                     'organization',
                                     full=True,
                                     null=True)
    head = fields.ForeignKey('primary_docs.api.resources.WorkerResource',
                             'head',
                             full=True,
                             null=True)
    masters = fields.ManyToManyField(
        'primary_docs.api.resources.WorkerResource',
        'masters',
        full=True,
        null=True)

    class Meta:
        queryset = models.Station.objects.all()
        resource_name = 'stations'
        list_allowed_methods = ['get', 'post', 'put', 'delete']
        detail_allowed_methods = ['get', 'post', 'put', 'delete']
        collection_name = 'stations'
        authorization = Authorization()
        authentication = MultiAuthentication(SessionAuthentication(),
                                             ApiKeyAuthentication())
        filtering = {'name': ALL, 'organization': ALL_WITH_RELATIONS}
Beispiel #28
0
class AnalyserResource(ModelResource):
    readings = fields.ManyToManyField(AirQualityReadingResource, 'readings')

    class Meta:
        queryset = Analyser.objects.all()
        resource_name = 'analysers'
        authorization = Authorization()
Beispiel #29
0
class TagResource(NestedResource):
    creator = fields.ForeignKey(UserResource, 'creator')
    collection = fields.ForeignKey(CollectionResource, "collection")
    segments = fields.ToManyField(
        'concertapp.audiosegments.api.AudioSegmentResource',
        'segments',
        null=True)
    events = fields.ManyToManyField('concertapp.event.api.EventResource',
                                    'events',
                                    null=True)

    class Meta:
        authentication = DjangoAuthentication()
        authorization = TagAuthorization()
        queryset = Tag.objects.all()
        filtering = {
            "segments": ALL,
        }

        nested = 'segments'

    def create_nested_event(self, obj, nested_obj, request):
        AudioSegmentTaggedEvent.objects.create(collection=obj.collection,
                                               audioSegment=nested_obj,
                                               tag=obj,
                                               user=request.user)
        return
Beispiel #30
0
class GeoserverStyleResource(ModelResource):
    """Styles API for Geoserver backend."""
    body = fields.CharField(attribute='sld_body', use_in='detail')
    name = fields.CharField(attribute='name')
    title = fields.CharField(attribute='sld_title')
    # layer_default_style is polymorphic, so it will have many to many
    # relation
    layer = fields.ManyToManyField(
        'geonode.api.resourcebase_api.LayerResource',
        attribute='layer_default_style',
        null=True)
    version = fields.CharField(attribute='sld_version', null=True, blank=True)
    style_url = fields.CharField(attribute='sld_url')
    workspace = fields.CharField(attribute='workspace', null=True)
    type = fields.CharField(attribute='type')

    class Meta:
        queryset = Style.objects.all()
        resource_name = 'styles'
        detail_uri_name = 'id'
        authorization = GeoNodeStyleAuthorization()
        allowed_methods = ['get']
        filtering = {
            'id': ALL,
            'title': ALL,
            'name': ALL,
            'layer': ALL_WITH_RELATIONS
        }

    def build_filters(self, filters=None, **kwargs):
        """Apply custom filters for layer."""
        filters = super(GeoserverStyleResource,
                        self).build_filters(filters, **kwargs)
        # Convert layer__ filters into layer_styles__layer__
        updated_filters = {}
        for key, value in filters.iteritems():
            key = key.replace('layer__', 'layer_default_style__')
            updated_filters[key] = value
        return updated_filters

    def populate_object(self, style):
        """Populate results with necessary fields

        :param style: Style objects
        :type style: Style
        :return:
        """
        style.type = 'sld'
        return style

    def build_bundle(self, obj=None, data=None, request=None, **kwargs):
        """Override build_bundle method to add additional info."""

        if obj is None and self._meta.object_class:
            obj = self._meta.object_class()

        elif obj:
            obj = self.populate_object(obj)

        return Bundle(obj=obj, data=data, request=request, **kwargs)