class DocumentResource(ModelResource): regions = fields.ToManyField(RegionResource, 'regions', full=True) geonode_page = fields.CharField(attribute='get_absolute_url', readonly=True) geonode_file = fields.FileField(attribute='doc_file') class Meta: queryset = Document.objects.all() resource_name = 'document' fields = [ 'title', 'date', ] include_resource_uri = False allowed_methods = ['get'] authentication = BasicAuthentication() cache = SimpleCache(timeout=10) filtering = { 'title': ALL, 'date': ALL_WITH_RELATIONS, }
class UserResource(ModelResource): orders = fields.ToManyField('api.api.OrderResource', 'orders', null=True, blank=True, readonly=True) address = fields.OneToOneField('api.api.AddressResource', 'address', full=True, null=True) class Meta: queryset = User.objects.all() resource_name = 'user' authorization = Authorization() always_return_data = True def hydrate(self, bundle): data_keys = bundle.data.keys() if 'id' not in data_keys: exists = User.objects.filter( username=bundle.data['username']).exists() if not exists: if 'password' not in bundle.data.keys(): bundle.data['password'] = '******' else: user = User.objects.get(username=bundle.data['username']) bundle.data['id'] = user.id else: user = User.objects.get(id=bundle.data['id']) # bundle.obj=user # if 'address' in bundle.data.keys(): # bundle.data['address']['user'] = bundle.obj if 'address' in data_keys: bundle.data['address']['user'] = bundle.obj return bundle def dehydrate(self, bundle): return bundle
class JingleSetResource(ModelResource): jingles = fields.ToManyField('abcast.api.JingleResource', 'jingle_set', null=True, full=True, max_depth=2) class Meta: queryset = JingleSet.objects.order_by('name').all() list_allowed_methods = [ 'get', ] detail_allowed_methods = [ 'get', ] resource_name = 'abcast/jingleset' excludes = [ 'updated', ] authentication = Authentication() authorization = Authorization() filtering = { 'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'], } def dehydrate(self, bundle): bundle.data['main_image'] = None if bundle.obj.main_image: opt = dict(size=(70, 70), crop=True, bw=False, quality=80) try: main_image = get_thumbnailer( bundle.obj.main_image).get_thumbnail(opt) bundle.data['main_image'] = main_image.url except: pass return bundle
class LogicalCluster(models.Model): """Model representing a cluster of varnish servers""" name = models.CharField(max_length=100, validators=[vcl_name_validator], unique=True) directors = fields.ToManyField('vaas.manager.api.DirectorResource', 'directors') reload_timestamp = models.DateTimeField(default=timezone.now) error_timestamp = models.DateTimeField(default=timezone.now) last_error_info = models.CharField(max_length=400, null=True, blank=True) def __unicode__(self): return "{} ({})".format(self.name, self.varnish_count()) def __eq__(self, other): if isinstance(other, self.__class__): return self.name == other.name else: return False def varnish_count(self): return VarnishServer.objects.filter(cluster=self).count()
class CustomFacetResource(ModelResource): group = fields.ForeignKey(GroupResource, 'group', null=True) business_units = fields.ToManyField(BusinessUnitResource, 'business_units', blank=True, null=True) class Meta: queryset = CustomFacet.objects.all() resource_name = 'custom_facet' filtering = { 'group': ALL_WITH_RELATIONS, 'business_units': ALL_WITH_RELATIONS, 'country': ALL, 'state': ALL, 'city': ALL, 'keyword': ALL, 'onet': ALL, 'always_show': ALL } authentication = ApiKeyAuthentication() throttle = SmartCacheDBThrottle()
class TagResource(ModelResource): count = fields.IntegerField(readonly=True) modules = fields.ToManyField( 'learning_modules.api.resources.ModuleTagResource', 'moduletag_set', related_name='tag', full=True) class Meta: queryset = Tag.objects.filter( modules__isnull=False).distinct().order_by("name") resource_name = 'tag' allowed_methods = ['get'] fields = ['id', 'name'] authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True include_resource_uri = False serializer = TagJSONSerializer() def dehydrate(self, bundle): return bundle def dehydrate_count(self, bundle): count = Module.objects.filter(tag__id=bundle.obj.id).count() return count def tag_detail(self, request, **kwargs): self.is_authenticated(request) self.throttle_check(request) name = kwargs.pop('name', None) modules = Module.objects.filter(tag__name=name) for m in modules: obj = ModuleResource().build_bundle(obj=m, request=request) response = HttpResponse(name + str(modules), content_type='') return response
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 PowerControlDeviceResource(DeleteablePowerObjectResource): """ An instance of a power control device, associated with a power control type """ device_type = fields.ToOneField( 'chroma_api.power_control.PowerControlTypeResource', 'device_type', full=True) outlets = fields.ToManyField( 'chroma_api.power_control.PowerControlDeviceOutletResource', 'outlets', full=True, null=True) def hydrate(self, bundle): bundle = super(PowerControlDeviceResource, self).hydrate(bundle) # We don't want to expose the PDU password via the API, so # we've added it to the excluded fields. We do, however, want to # allow it to be set, so we have to jam it into the object # ourselves. if 'password' in bundle.data: bundle.obj.password = bundle.data['password'] return bundle class Meta: queryset = PowerControlDevice.objects.all() resource_name = 'power_control_device' authorization = DjangoAuthorization() authentication = AnonymousAuthentication() validation = ResolvingFormValidation(form_class=PowerControlDeviceForm) ordering = ['name'] filtering = {'name': ['exact']} excludes = ['not_deleted', 'password'] list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'put', 'delete'] readonly = ['id'] always_return_data = True
class WorkerPoolResource(ModelResource): """ RESTful resource for worker-pools. """ workers = fields.ToManyField( 'job_runner.apps.job_runner.api.WorkerResource', 'workers') def build_filters(self, filters=None): if filters is None: filters = {} orm_filters = super(WorkerPoolResource, self).build_filters(filters) if 'project_id' in filters: orm_filters.update({'project__id': filters['project_id']}) return orm_filters class Meta: queryset = WorkerPool.objects.all() resource_name = 'worker_pool' list_allowed_methods = ['get'] detail_allowed_methods = ['get'] fields = [ 'id', 'title', 'description', 'enqueue_is_enabled', ] filtering = { 'title': 'exact', } authentication = MultiAuthentication(SessionAuthentication(), HmacAuthentication()) authorization = ModelAuthorization( api_key_path='workers__api_key', user_groups_path='project__groups', )
class ExperimentParameterSetAppResource( tardis.tardis_portal.api.ParameterSetResource): def __init__(self, *args, **kwargs): self.as_super = super(ExperimentParameterSetAppResource, self) self.as_super.__init__(*args, **kwargs) experiment = fields.ForeignKey( 'tardis.apps.imagetrove.api.ExperimentAppResource', 'experiment') parameters = fields.ToManyField( 'tardis.apps.imagetrove.api.ExperimentParameterAppResource', 'experimentparameter_set', related_name='parameterset', full=True, null=True) def save_m2m(self, bundle): # super(tardis.tardis_portal.api.ExperimentParameterSetResource, self).save_m2m(bundle) self.as_super.save_m2m(bundle) class Meta(tardis.tardis_portal.api.ParameterSetResource.Meta): queryset = ExperimentParameterSet.objects.all() resource_name = 'experimentparameterset'
class ChannelList(ModelResource): readings = fields.ToManyField('sensors.api.resources.ReadingList', 'reading_set', full=True, null=True) class Meta: queryset = Channel.objects.all() resource_name = 'channel' allowed_methods = ['get'] authentication = KeyOnlyAuthentication() authorization = DjangoAuthorization() always_return_data = True detail_uri_name = 'id' filtering = { 'name': ALL, } def dehydrate_tags(self, bundle): return bundle.obj.tags
class ScheduleResource(ModelResource): activityschedule = fields.ToManyField( 'oppia.api.resources.ActivityScheduleResource', 'activityschedule_set', related_name='schedule', full=True, null=True) class Meta: queryset = Schedule.objects.all() resource_name = 'schedule' allowed_methods = ['get'] fields = ['id', 'title', 'lastupdated_date'] authentication = ApiKeyAuthentication() authorization = Authorization() always_return_data = True include_resource_uri = False def dehydrate(self, bundle): bundle.data['version'] = bundle.data['lastupdated_date'].strftime( "%Y%m%d%H%M%S") return bundle
class PersonResource(ModelResource): identifiers = fields.ToManyField(IdentifierResource, 'identifiers', full=True) class Meta: queryset = PopoloPerson.objects.all().prefetch_related('identifiers') resource_name = 'person' authentication = ApiKeyAuthentication() filtering = { 'identifiers': ALL_WITH_RELATIONS, } def obj_get_list(self, bundle, **kwargs): result = super(PersonResource, self).obj_get_list(bundle, **kwargs) filters = bundle.request.GET.copy() if 'has_contacts' in filters: # Count the number of contacts the person has filters['has_contacts'] = filters['has_contacts'].lower() if filters['has_contacts'] == 'true': result = result.has_contacts() elif filters['has_contacts'] == 'false': result = result.doesnt_have_contacts() else: raise InvalidFilterError( "'has_contacts' field must either be 'true' or 'false'.") if 'instance_id' in filters: result = result.filter( writeit_instances__id=filters['instance_id']) return result def dehydrate(self, bundle): bundle.data['resource_uri'] = bundle.obj.uri_for_api() bundle.data['popit_id'] = bundle.obj.old_popit_id bundle.data['popit_url'] = bundle.obj.uri_for_api() return bundle
class OfflineRespondantResource(SurveyModelResource): responses = fields.ToManyField('apps.survey.api.OfflineResponseResource', 'responses', null=True, blank=True) survey = fields.ToOneField('apps.survey.api.SurveyResource', 'survey', null=True, blank=True) user = fields.ToOneField('apps.account.api.UserResource', 'user', null=True, blank=True) class Meta: always_return_data = True queryset = Respondant.objects.all() authorization = UserObjectsOnlyAuthorization() authentication = Authentication() ordering = ['-ts'] def obj_create(self, bundle, **kwargs): if not bundle.request.user.is_authenticated(): return None return super(OfflineRespondantResource, self).obj_create(bundle, user=bundle.request.user) def save_related(self, bundle): resource_uri = self.get_resource_uri(bundle.obj) user_uri = self.get_resource_uri(bundle.request.user) for response in bundle.data.get('responses'): response['respondant'] = resource_uri response['user'] = user_uri
class CurrentUserResource(LinkUserResource): top_level_folders = fields.ToManyField( FolderResource, lambda bundle: bundle.request.user.top_level_folders(), readonly=True, full=True) class Meta(DefaultResource.Meta): resource_name = 'user' queryset = LinkUser.objects.all()[:0] # needed for /schema to render authentication = CurrentUserAuthentication() authorization = CurrentUserAuthorization() list_allowed_methods = [] detail_allowed_methods = ['get'] # Limit the url to only the first route (/resource) and schema to allow nested resources def base_urls(self): return super(CurrentUserResource, self).base_urls()[0:2] # Map the detail view to the list view so that detail shows at the resource root def dispatch_list(self, request, **kwargs): return self.dispatch_detail(request, **kwargs) def obj_get(self, bundle, **kwargs): ''' Always returns the logged in user. ''' return bundle.request.user # Build the URI (included in the JSON response) to match our remapped dispatch_list def get_resource_uri(self, bundle_or_obj=None, url_name='api_dispatch_list'): bundle_or_obj = None try: return self._build_reverse_url( url_name, kwargs=self.resource_uri_kwargs(bundle_or_obj)) except NoReverseMatch: return ''
class ArticleResource(ModelResource): issue = fields.ForeignKey(IssueResource, 'issue') section = fields.ForeignKey(SectionResource, 'section') tags = fields.ToManyField('brubeck.tagging.api.TagResource', 'tags') photos = fields.ToManyField('brubeck.photography.api.PhotoResource', 'photos') videos = fields.ToManyField('brubeck.multimedia.api.VideoResource', 'videos') audio_clips = fields.ToManyField('brubeck.multimedia.api.AudioResource', 'audio_clips') slideshows = fields.ToManyField('brubeck.multimedia.api.SlideshowResource', 'slideshows') podcast_episodes = fields.ToManyField( 'brubeck.podcasts.api.PodcastResource', 'podcast_episodes') photos = fields.ToManyField('brubeck.design.api.GraphicResource', 'graphics') class Meta: queryset = Article.objects.all() resource_name = 'article' allowed_methods = ['get']
class PackageResource(ModelResource): releases = fields.ToManyField("packages.api.ReleaseResource", "releases") downloads = fields.IntegerField("downloads") latest = fields.ToOneField("packages.api.InlineReleaseResource", "latest", full=True) class Meta: allowed_methods = ["get"] cache = SimpleCache() fields = ["created", "downloads_synced_on", "downloads", "name"] filtering = { "name": ALL, "created": ALL, "downloads_synced_on": ALL, } include_absolute_url = True ordering = ["created", "downloads_synced_on"] queryset = Package.objects.all() resource_name = "package" def override_urls(self): return [ url(r"^(?P<resource_name>%s)/(?P<name>[^/]+)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view("dispatch_detail"), name="api_dispatch_detail"), ] def get_resource_uri(self, bundle_or_obj): kwargs = { "resource_name": self._meta.resource_name, } if isinstance(bundle_or_obj, Bundle): kwargs["name"] = bundle_or_obj.obj.name else: kwargs["name"] = bundle_or_obj.name if self._meta.api_name is not None: kwargs["api_name"] = self._meta.api_name return self._build_reverse_url("api_dispatch_detail", kwargs=kwargs)
class PresenterResource(ModelResource): platform = fields.ForeignKey(PlatformResource, 'platform', full=True) tags = fields.ToManyField(TagResource, 'tag', full=True) detail = fields.OneToOneField(PresenterDetailResource, 'presenterdetail', full=True) def apply_sorting(self, obj_list, options=None): if options and "sort" in options: if options['sort'] == 'showing': return obj_list.order_by('-presenterdetail__showing') else: return obj_list.order_by(options['sort']) return super(PresenterResource, self).apply_sorting(obj_list, options) # showing = fields.BooleanField(readonly=True) # def dehydrate_showing(self, bundle): # print type(bundle.obj), type(bundle.data) # print dir(type(bundle.obj)) # return bundle.obj.presenterdetail.showing # def build_filters(self, filters=None): # print filters # if filters is None: # filters = {} # orm_filters = super(PresenterResource, self).build_filters(filters) # print type(orm_filters), orm_filters # if 'q' in filters: # pass # return orm_filters class Meta: queryset = Presenter.objects.all() allowed_methods = ['get'] filtering = { "nickname": ALL, }
class GrammarResource(ModelResource): content = fields.ToManyField(ContentResource, 'content_set', related_name='content', blank=True, null=True, use_in='detail', full=True) category = fields.ForeignKey('api.category.CategoryResource', 'category', blank=True, null=True, full=True) task_sequence = fields.ForeignKey('api.task_sequence.TaskSequenceResource', 'tasks', blank=True, full=True, null=True, use_in='detail') class Meta: queryset = Grammar.objects.all() allowed_methods = ['get'] def build_title(self, memo, content): lang = content.source_lang.short_code memo[lang] = content return memo def dehydrate(self, bundle): bundle.data['titles'] = reduce( self.build_title, Content.objects.filter(grammar_ref=bundle.obj), {}) return bundle
class GroupProfileResource(ModelResource): categories = fields.ToManyField(GroupCategoryResource, 'categories', full=True) member_count = fields.CharField() manager_count = fields.CharField() logo_url = fields.CharField() detail_url = fields.CharField() class Meta: queryset = GroupProfile.objects.all() resource_name = 'group_profile' allowed_methods = ['get'] filtering = { 'title': ALL, 'slug': ALL, 'categories': ALL_WITH_RELATIONS, } ordering = ['title', 'last_modified'] authorization = GroupProfileAuthorization() def dehydrate_member_count(self, bundle): """Provide relative URL to the geonode UI's page on the group""" return bundle.obj.member_queryset().count() def dehydrate_manager_count(self, bundle): """Provide relative URL to the geonode UI's page on the group""" return bundle.obj.get_managers().count() def dehydrate_detail_url(self, bundle): """Return relative URL to the geonode UI's page on the group""" if bundle.obj.slug: return reverse('group_detail', args=[bundle.obj.slug]) else: return None def dehydrate_logo_url(self, bundle): return bundle.obj.logo_url
class ScanResource(BaseModelResource): scan_settings = fields.ForeignKey(ScanSettingsResource, 'scan_settings', null=False) ipscans = fields.ToManyField( IPScanResource, attribute=lambda bundle: IPScan.objects.filter(scan__id=bundle.obj.id) if IPScan.objects.filter(scan__id=bundle.obj.id) != [] else [], full=True, null=True) class Meta: resource_name = 'scans' queryset = Scan.objects.all() list_allowed_methods = ['get'] detail_allowed_methods = ['get'] include_resource_uri = True filtering = {'id': ALL, 'date': ALL, 'scan_settings': ALL} authentication = DojoApiKeyAuthentication() authorization = UserScanAuthorization() serializer = Serializer(formats=['json'])
class VoteResource(BaseResource): class Meta(BaseResource.Meta): queryset = Vote.objects.all() allowed_methods = ['get'] exclude_from_list_view = [ 'members', ] filtering = dict(member=ALL, member_for=ALL, member_against=ALL) members = fields.ToManyField(MemberResource, 'votes', full=False) def build_filters(self, filters={}): orm_filters = super(VoteResource, self).build_filters(filters) if 'member' in filters: orm_filters["voteaction__member"] = filters['member'] if 'member_for' in filters: orm_filters["voteaction__member"] = filters['member_for'] orm_filters["voteaction__type"] = 'for' if 'member_against' in filters: orm_filters["voteaction__member"] = filters['member_against'] orm_filters["voteaction__type"] = 'against' return orm_filters
class OfflineRespondantResource(AuthSurveyModelResource): responses = fields.ToManyField(OfflineResponseResource, 'response_set', null=True, blank=True) survey = fields.ToOneField('apps.survey.api.SurveyResource', 'survey', null=True, blank=True) class Meta(AuthSurveyModelResource.Meta): always_return_data = True queryset = Respondant.objects.all() ordering = ['-ts'] def obj_create(self, bundle, **kwargs): return super(OfflineRespondantResource, self).obj_create(bundle, surveyor=bundle.request.user) def save_related(self, bundle): resource_uri = self.get_resource_uri(bundle.obj) for response in bundle.data.get('responses'): response['respondant'] = resource_uri
class VenueResource(ModelResource): events = fields.ToManyField('api.resources.EventResource', 'venue', full=True, null=True) class Meta: queryset = Venue.objects.all() list_allowed_methods = ['get'] resource_name = 'venues' collection_name = 'venues' include_resource_uri = False # Add thumbnail field def dehydrate(self, bundle): if bundle.obj.profile_thumbnail: bundle.data['profile_thumbnail'] = bundle.obj.profile_thumbnail.url return bundle # Remove the wrapper def alter_list_data_to_serialize(self, request, data): if self.Meta.collection_name in data and len(data[self.Meta.collection_name]) > 0: # only return the first result, avoid the "meta" field return data[self.Meta.collection_name] else: return []
class ResponseResource(ModelResource): question = fields.ForeignKey(QuestionResource, 'question') props = fields.ToManyField('quiz.api.resources.ResponsePropsResource', 'responseprops_set', related_name='response', full=True, null=True) class Meta: queryset = Response.objects.all() allowed_methods = ['get', 'post'] fields = ['id', 'order', 'title', 'score'] resource_name = 'response' include_resource_uri = True serializer = PrettyJSONSerializer() authentication = ApiKeyAuthentication() authorization = Authorization() validation = QuestionOwnerValidation() always_return_data = True def hydrate(self, bundle, request=None): bundle.obj.owner = User.objects.get(pk=bundle.request.user.id) return bundle
class ValidationReportResource(Resource): validation_results = fields.ToManyField(ValidationResultResource, 'validation_results', full=True, null=True) validation_status = fields.CharField(attribute='validation_status', null=True) task_status = fields.CharField(attribute='task_status') class Meta: resource_name = 'validation_report' list_allowed_methods = ['get'] authorization = DjangoAuthorization() authentication = VaasMultiAuthentication(ApiKeyAuthentication(), SessionAuthentication()) fields = ['validation_results', 'validation_status', 'task_status'] include_resource_uri = False def obj_get(self, bundle, **kwargs): return prepare_report_from_task(kwargs['pk']) def get_object_list(self, request): return None
class DayResource(ModelResource): ''' Resource for training days ''' workout = fields.ToOneField(WorkoutResource, 'training') days_of_week = fields.ToManyField(DaysOfWeekResource, 'day') def authorized_read_list(self, object_list, bundle): ''' Filter to own objects ''' return object_list.filter(training__user=bundle.request.user) class Meta: queryset = Day.objects.all() authentication = ApiKeyAuthentication() authorization = UserObjectsOnlyAuthorization() filtering = { 'id': ALL, 'description': ALL, 'workout': ALL_WITH_RELATIONS }
class WorkflowResource(ModelResource): input_relationships = fields.ToManyField("core.api.WorkflowInputRelationshipsResource", 'input_relationships', full=True) class Meta: queryset = Workflow.objects.filter(is_active=True).order_by('name') detail_resource_name = 'workflow' resource_name = 'workflow' detail_uri_name = 'uuid' allowed_methods = ['get'] fields = ['name', 'uuid', 'summary'] def dehydrate(self, bundle): # detect if detail if self.get_resource_uri(bundle) == bundle.request.path: # detail detected, add graph as json try: bundle.data['graph'] = json.loads(bundle.obj.graph) except ValueError: logger.error("Failed to decode workflow graph into dictionary for workflow " + str(bundle.obj) + ".") # don't include in response if error occurs bundle.data['author'] = bundle.obj.get_owner() bundle.data['galaxy_instance_identifier'] = bundle.obj.workflow_engine.instance.api_key return bundle
class SetResource(ModelResource): ''' Resource for training sets ''' day = fields.ToOneField(DayResource, 'exerciseday') exercises = fields.ToManyField(ExerciseResource, 'exercises') def authorized_read_list(self, object_list, bundle): ''' Filter to own objects ''' return object_list.filter( exerciseday__training__user=bundle.request.user) class Meta: queryset = Set.objects.all() authentication = ApiKeyAuthentication() authorization = UserObjectsOnlyAuthorization() filtering = {'id': ALL, 'day': ALL_WITH_RELATIONS, 'order': ALL, 'sets': ALL}
class PermissionResourceMixin(ModelResource): def dehydrate_permissions(self, bundle): """ Return the simple version of the permission (without the instance name) :param bundle: :return: """ return map( lambda permission: permission.data.get('codename', '').split('_')[ 0], bundle.data['permissions']) # Returns the permissions of the bundle obj for the username. @using_bundle_cache def permission_query(bundle): return bundle.obj.permissions_for_user(bundle.request.GET['username']) permissions = fields.ToManyField(PermissionResource, attribute=permission_query, full=True, null=True, readonly=True) def permission_get_object_list(self, request, object_list): """ Filter by our Permissions :param request: :param object_list: :return: """ model = self._meta.queryset.model # Find all the groups of this user groups = request.user.groups.all() permitted_ids = model.permitted_ids(groups, object_list) # Filter by permitted ids return object_list.filter( id__in=map(lambda id: int(id), permitted_ids))