class PostResource(MultiPartResource, ModelResource): image = fields.FileField(attribute="image", null=True, blank=True) video = fields.FileField(attribute="video", null=True, blank=True) # comments = fields.ToManyField(CommentResource, 'comments', full=True) class Meta: queryset = Post.objects.all().order_by('-created') resource_name = 'posts' serializer = Serializer(formats=['json']) allowed_methods = ['get', 'post'] always_return_data = True authorization = Authorization() def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/(?P<pk>.*?)/get_comments%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_comments'), name="api_get_comments"), ] def get_comments(self, request, **kwargs): post = Post.objects.filter(id=kwargs['pk']).first() queryset = post.get_comments() return self.create_response(request, { 'success': True, 'objects': list(queryset) })
class FeaturedMapResource(ModelResource): """ WFP Featured Maps API """ owner = fields.ToOneField(ProfileResource, 'owner', full=True) custom_thumbnail = fields.FileField() def dehydrate_custom_thumbnail(self, bundle): from wfp.gis.models import CustomThumbnail rb = bundle.obj thumb = CustomThumbnail.objects.filter(object_id=rb.id, content_type=rb.polymorphic_ctype).first() # we cascade to default thumbnail if custom does not exist thumb_url = rb.thumbnail_url if thumb: thumb_url = '%s%s' % (settings.MEDIA_URL, thumb.thumbnail) return thumb_url class Meta: queryset = ResourceBase.objects.filter(featured=True).order_by('-date') if settings.RESOURCE_PUBLISHING: queryset = queryset.filter(is_published=True) resource_name = 'wfp-featured-maps' authorization = GeoNodeAuthorization() allowed_methods = ['get'] filtering = {'title': ALL, 'keywords': ALL_WITH_RELATIONS, 'regions': ALL_WITH_RELATIONS, 'category': ALL_WITH_RELATIONS, 'owner': ALL_WITH_RELATIONS, 'date': ALL, } ordering = ['date', 'title', 'popular_count'] max_limit = None
class RRR(RR): upload_to = os.path.join( settings.MEDIA_ROOT, getattr( settings, 'RESOURCE_FOLDER_%sS_IN_MEDIA_ROOT' % dict(R.md.RESOURCE_TYPE_CHOICES)[ R.md.resource_type].upper())) object_id = tastypie_fields.IntegerField(attribute='object_id', null=True, blank=True) file = tastypie_fields.FileField(attribute='file', null=True, blank=True) def save(self, bundle, skip_errors=False): bundle.obj.file = self.handle_uploaded_file( bundle.data['file']) return super(RRR, self).save(bundle, skip_errors) def handle_uploaded_file(self, f): dst = os.path.join(self.upload_to, generate_filename(str(f))) dst_dir = os.path.dirname(dst) if not os.path.exists(dst_dir): os.makedirs(dst_dir) with open(dst, 'wb+') as dst_file: for chunk in f.chunks(): dst_file.write(chunk) dst_file.close() return dst.replace(settings.MEDIA_ROOT, '')
class PhotoResource(MultipartResource, ModelResource): thumbnail = fields.FileField('image__thumbnail', readonly=True) class Meta: queryset = Photo.objects.all() authorization = PhotoAuthorization( session_key_field='user_session_key') def dehydrate(self, bundle): """ Don't return session keys """ del bundle.data['user_session_key'] return bundle def obj_create(self, bundle, **kwargs): # set the session key from cookies return super(PhotoResource, self).obj_create( bundle, user_session_key=bundle.request.session.session_key) def hydrate_image(self, bundle): if 'image' in bundle.data: try: bundle.data['location'] = geojson_from_exif( bundle.data['image']) except NoGPSInfoException: pass return bundle
class DocumentResource(BaseModelResource): docfile = fields.FileField(attribute="csv", null=True, blank=True) class Meta(BaseModelResource.Meta): queryset = Document.objects.all().order_by('-created_at').values() max_limit = 10 resource_name = 'source_doc' filtering = { "id": ALL, } def obj_create(self, bundle, **kwargs): ''' If post, create file and return the JSON of that object. If get, just query the source_doc table with request parameters ''' doc_data = bundle.data['docfile'] try: doc_id = bundle.data['id'] except KeyError: doc_id = None try: doc_title = bundle.data['doc_title'] + '-' + str(int(time.time())) except KeyError: doc_title = doc_data[:10] new_doc = self.post_doc_data(doc_data, bundle.request.user.id, doc_title, doc_id) bundle.obj = new_doc bundle.data['id'] = new_doc.id return bundle def post_doc_data(self, post_data, user_id, doc_title, doc_id): # when posting from ODK, i dont add the file_meta.. from the webapp # i do. I should change so the post requests are consistent but # tryign to get this working for now. try: file_meta, base64data = post_data.split(',') except ValueError: base64data = post_data file_content = ContentFile(base64.b64decode(base64data)) file_header = file_content.readline() sd, created = Document.objects.update_or_create( id=doc_id, defaults={'doc_title': doc_title, 'created_by_id': user_id, \ 'file_header': file_header} ) sd.docfile.save(sd.guid, file_content) return sd
class ArtResource(MultipartResource, ModelResource): #artImage = fields.FileField(attribute="artImage", null=True, blank=True) artThumb = fields.FileField(attribute="artThumb", null=True, blank=True) class Meta: queryset = Art.objects.all() resource_name = 'art' authorization = Authorization()
class AboutMeResource(ModelResource): image = fields.FileField(attribute='image', null=True, readonly=True) class Meta: queryset = FacebookCustomUserActive.objects.all() resource_name = 'me' fields = ['id', 'first_name', 'last_name', 'facebook_id', 'image'] authentication = JSONWebTokenAuthentication() authorization = Authorization() filtering = { 'first_name': ALL } def get_object_list(self, request): return super(AboutMeResource, self).get_object_list(request).\ filter(pk=request.user.id) def dehydrate(self, bundle): raw_data = {} user_id = bundle.obj.id # if bundle.obj.raw_data: # raw_data = json.loads(bundle.obj.raw_data) bundle.data['position'] = get_current_position(bundle.obj) bundle.data['lives_in'] = get_lives_in(bundle.obj) bundle.data.update(raw_data) bundle.data['goals_count'] = Goal.objects.filter( user_id=user_id).count() bundle.data['offers_count'] = Offer.objects.\ filter(user_id=user_id).count() bundle.data['interest_count'] = Interest.objects.\ filter(user=user_id).count() return bundle
class DataFileAppResource(tardis.tardis_portal.api.MyTardisModelResource): dataset = fields.ForeignKey(tardis.tardis_portal.api.DatasetResource, 'dataset') parameter_sets = fields.ToManyField( 'tardis.apps.imagetrove.api.DatafileParameterSetAppResource', 'datafileparameterset_set', related_name='datafile', full=True, null=True) datafile = fields.FileField() replicas = fields.ToManyField('tardis.tardis_portal.api.ReplicaResource', 'file_objects', related_name='datafile', full=True, null=True) temp_url = None class Meta(tardis.tardis_portal.api.MyTardisModelResource.Meta): queryset = DataFile.objects.all() filtering = { 'directory': ('exact', 'startswith'), 'dataset': ALL_WITH_RELATIONS, 'filename': ('exact', ), } resource_name = 'dataset_file'
class FotosResource(MultipartResourceMixin, ModelResource): sitio = fields.ForeignKey(SitiosResource, 'sitio') imagen = fields.FileField(attribute="imagen", null=True, blank=True) resource_name = 'fotos' class Meta: queryset = Fotos.objects.all() authorization = Authorization() authorization = Authorization() authentication = ApiKeyAuthentication() filtering = { "sitio": ALL_WITH_RELATIONS, } def prepend_urls(self): return [ #url to download image file. url(r"^(?P<resource_name>%s)/(?P<pk>\w+)/imagen/$" % self._meta.resource_name, self.wrap_view('get_image'), name="api_get_image"), ] # Vista que permite descargar las imagenes def get_image(self, request, **kwargs): obj = Fotos.objects.get(id=kwargs['pk']) image_file = obj.imagen return HttpResponse(image_file.read(), content_type="image/jpeg")
class PictureResource(MultipartResource, ModelResource): file = fields.FileField(attribute="file", null=True, blank=True) class Meta: queryset = Picture.objects.all() allowed_methods = ['post'] authentication = Authentication() authorization = Authorization()
class LocationResource(MongoDBResource): id = fields.CharField(attribute="_id") analysis_id = fields.CharField(attribute="analysis_id") url_id = fields.CharField(attribute="url_id") content_id = fields.CharField(attribute="content_id") content_type = fields.CharField(attribute="content_type", null=True) mime_type = fields.CharField(attribute="mime_type", null=True) flags = fields.DictField(attribute="flags", null=True) md5 = fields.CharField(attribute="md5", null=True) sha256 = fields.CharField(attribute="sha256", null=True) size = fields.IntegerField(attribute="size", null=True) content_file = fields.FileField(attribute="content_file", null=True) class Meta: resource_name = 'location' authentication = ApiKeyAuthentication() object_class = Document collection = "locations" detail_uri_name = "_id" filtering = { 'analysis_id': ['exact'], } def prepend_urls(self): return [ #url to download file. url(r"^(?P<resource_name>%s)/(?P<pk>\w+)/file/$" % self._meta.resource_name, self.wrap_view('get_file'), name="api_get_file"), ] def dehydrate_content_file(self, bundle): return '/api/v1/%s/%s/file/' % (self._meta.resource_name, bundle.obj.content_id) def get_file(self, request, **kwargs): # Database MongoClient dbfs = MongoClient().thugfs fs = GridFS(dbfs) try: download_file = base64.b64decode( fs.get(ObjectId(kwargs['pk'])).read()) except: raise Http404("File not found") hexdumped = False mime = magic.from_buffer(download_file, mime=True) if not is_text(mime): download_file = hexdump.hexdump(download_file, result='return') hexdumped = True # Ensure to use Unicode for the content, else JsonResopnse may fail if not isinstance(download_file, unicode): download_file = unicode(download_file, errors='ignore') return HttpResponse(download_file, content_type=mime)
class MapaResource(ModelResource): salas = fields.ToManyField(SalaResource, 'salas', related_name='mapa', null=True, full=True) imagen = fields.FileField(attribute="imagen", null=True, blank=True) class Meta: resource_name = 'mapas' queryset = Mapa.objects.all() authorization = Authorization() allowed_methods = ['get', 'post', 'put', 'delete'] always_return_data = True
class CelllineBatchImagesResource(ModelResource): image_file = fields.FileField('image') image_md5 = fields.CharField('md5') magnification = fields.CharField('magnification', null=True) time_point = fields.CharField('time_point', null=True) class Meta: queryset = CelllineBatchImages.objects.all() include_resource_uri = False fields = ('image_file', 'image_md5', 'magnification', 'time_point')
class CelllineInformationPackResource(ModelResource): clip_file = fields.FileField('clip_file') md5 = fields.CharField('md5') version = fields.CharField('version', null=True) class Meta: queryset = CelllineInformationPack.objects.all() include_resource_uri = False fields = ('clip_file', 'md5', 'version', 'updated')
class PhotoList(ModelResource): large = fields.FileField('large') thumb = fields.FileField('thumb') class Meta: queryset = Photo.objects.all() resource_name = 'photo' 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 SongResource(MultipartResource, ModelResource): songFile = fields.FileField(attribute="songFile", null=True, blank=True) artist = fields.ForeignKey(ArtistResource, 'artist', full=True) art = fields.ForeignKey(ArtResource, 'art', full=True) user = fields.ForeignKey(UserResource, 'submitedByUser', full=True) class Meta: authorization = Authorization() queryset = Song.objects.all() resource_name = 'song' #authentication = BitAuthAuthentication()
class OrganisationResource(Resource): logo = fields.FileField() creator = fields.ToOneField('app.api.UserResource', 'creator') owner = fields.ToOneField('app.api.UserResource', 'owner') class Meta(Resource.Meta): queryset = Organisation.objects.filter(is_deleted=False) fields = [ 'id', 'name', 'logo', 'plan', 'slug', 'url', 'creator', 'owner' ] resource_name = 'orgs'
class UserProfileResource(ModelResource): image = fields.FileField(attribute='image', null=True, readonly=True) class Meta: queryset = FacebookCustomUserActive.objects.all() resource_name = 'user_profile' fields = ['first_name', 'last_name', 'facebook_id', 'image', 'about_me'] authentication = JSONWebTokenAuthentication() authorization = Authorization() filtering = { 'first_name': ALL }
class FacebookPhotoResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') cropped_photo = fields.FileField(attribute="cropped_photo", null=True, blank=True, readonly=True) class Meta: queryset = FacebookPhoto.objects.all() resource_name = 'photo' ordering = ['order'] always_return_data = True authentication = JSONWebTokenAuthentication() authorization = Authorization() def get_object_list(self, request): user = request.GET.get('user_id', request.user.id) return super(FacebookPhotoResource, self).get_object_list(request).\ filter(user_id=user) def dehydrate(self, bundle): photo_url = bundle.data.get('photo', '') if not photo_url.startswith('/media/') and \ not photo_url.startswith('http'): bundle.data['photo'] = u'/media/{}'.format(bundle.data['photo']) return bundle def obj_create(self, bundle, **kwargs): return super(FacebookPhotoResource, self).obj_create(bundle, **kwargs) def obj_update(self, bundle, skip_errors=False, **kwargs): return super(FacebookPhotoResource, self).obj_update(bundle, **kwargs) def obj_delete(self, bundle, **kwargs): qs = FacebookPhoto.objects.filter(user_id=bundle.request.user.id) count = qs.count() max_order = qs.aggregate(Max('order')).get('order__max') photo_id = kwargs.get('pk') target = qs.get(pk=photo_id) try: if count == 1: raise Unauthorized() elif target.order == 0: qs.exclude(order=0).update(order=F('order') - 1) elif target.order == max_order: pass else: qs.filter(order__gt=target.order).update(order=F('order') - 1) except Unauthorized as e: self.unauthorized_result(e) return super(FacebookPhotoResource, self).obj_delete(bundle, **kwargs)
class TweetResource(ModelResource): published = fields.BooleanField(default=False) pub_datetime = fields.DateTimeField(null=True, blank=True) user = fields.ForeignKey(UserResource, 'user') image1 = fields.FileField(attribute="image1") image2 = fields.FileField(attribute="image2") image3 = fields.FileField(attribute="image3") image4 = fields.FileField(attribute="image4") class Meta: queryset = Tweet.objects.select_related('user').all() resource_name = 'tweet' filtering = { 'user': ALL_WITH_RELATIONS, 'pub_datetime': ['exact', 'lt', 'lte', 'gte', 'gt'], } allowed_methods = ['post'] authentication = ApiKeyAuthentication() authorization = Authorization() def hydrate(self, bundle, request=None): bundle.obj.user = TwitterUser.objects.get(pk=bundle.request.user.id) return bundle
class FileStorageResource(ModelResource): mapping_preset_id = fields.ForeignKey(MappingPresetObjectResource, "mapping_preset_id") file_type = fields.ForeignKey(FileTypeDictResource, "file_type") file_obj = fields.FileField(attribute="file_obj") class Meta: queryset = FileStorage.objects.all() resource_name = "presetfile" allowed_methods = ["get"] filtering = { 'mapping_preset_id': ALL_WITH_RELATIONS, 'file_type': ALL_WITH_RELATIONS, 'file_name': ALL }
class ConnectionsSearchResource(Resource): id = fields.CharField(attribute='id') first_name = fields.CharField(attribute='first_name') friend_id = fields.CharField(attribute='friend_id') image = fields.FileField(attribute="image", null=True, blank=True) class Meta: resource_name = 'connectionssearch' authentication = JSONWebTokenAuthentication() authorization = Authorization() def detail_uri_kwargs(self, bundle_or_obj): kwargs = {} if isinstance(bundle_or_obj, Bundle): kwargs['pk'] = bundle_or_obj.obj.id else: kwargs['pk'] = bundle_or_obj.id return kwargs def get_object_list(self, request): results = [] _first_name = request.GET.get('first_name', '') current_user = request.user.id friends = NeoFourJ().get_my_friends_icontains_name( current_user, _first_name) users = FacebookCustomUserActive.objects.filter(id__in=friends) for friend in users: new_obj = A() new_obj.id = friend.id new_obj.first_name = friend.first_name new_obj.friend_id = friend.id new_obj.image = FacebookPhoto.objects.profile_photo( new_obj.friend_id) results.append(new_obj) return sorted(results, key=lambda x: x.first_name, reverse=False) def obj_get_list(self, bundle, **kwargs): # Filtering disabled for brevity... return self.get_object_list(bundle.request) def rollback(self, bundles): pass def obj_get(self, bundle, **kwargs): pass
class MakerScienceProfileResourceLight(ModelResource, SearchableMakerScienceResource): parent_id = fields.IntegerField('parent__id') first_name = fields.CharField('parent__user__first_name') last_name = fields.CharField('parent__user__last_name') address_locality = fields.CharField('location__address__address_locality', null=True) avatar = fields.FileField("parent__mugshot", null=True, blank=True) date_joined = fields.DateField("parent__user__date_joined") class Meta: queryset = MakerScienceProfile.objects.all() allowed_methods = ['get'] resource_name = 'makerscience/profilelight' authentication = AnonymousApiKeyAuthentication() authorization = DjangoAuthorization() always_return_data = True detail_uri_name = 'slug' excludes = ["bio", "facebook", "linkedin", "twitter", "website"] filtering = { 'id': [ 'exact', ], 'parent_id': [ 'exact', ], 'slug': [ 'exact', ] } limit = 6 def dehydrate(self, bundle): bundle.data[ "lng"] = bundle.obj.location.geo.x if bundle.obj.location.geo else "" bundle.data[ "lat"] = bundle.obj.location.geo.y if bundle.obj.location.geo else "" return bundle def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/search%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('ms_search'), name="api_ms_search"), ]
class ImageResource(CommonModelResource): attach_to = fields.ForeignKey(CommonResource, 'attach_to', null=True) image = fields.FileField(attribute='image') image_thumbnail_1x = SorlThumbnailField( attribute='image', thumb_options={'geometry': '280x280'}) image_thumbnail_2x = SorlThumbnailField( attribute='image', thumb_options={'geometry': '800x800'}) image_thumbnail_3x = SorlThumbnailField( attribute='image', thumb_options={'geometry': '1024x1024'}) unicode_string = fields.CharField(attribute='unicode_string', null=True) class Meta: queryset = Image.objects.all() resource_name = 'image' authentication = CommonApiKeyAuthentication()
class FloorResource(MultipartResource, ModelResource): """ The resource for a Floor Allows filtering on building_name and floor_number """ image = fields.FileField(attribute='image', null=True, blank=True) class Meta(CommonMeta): queryset = Floor.objects.all() fields = [ 'building_name', 'floor_number', 'image_width', 'image_height', 'image' ] filtering = { 'building_name': ALL, 'floor_number': ALL, }
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', ])
class FarmerResource(BaseResource): village = fields.ForeignKey(VillageResource, 'village', full=True) image = fields.FileField(attribute='img', null=True, blank=True) class Meta: limit = 0 max_limit = 0 allowed_methods = ["get", "post", "put", "delete"] queryset = Farmer.objects.all() resource_name = 'farmer' always_return_data = True authorization = VillageAuthorization('village_id__in') authentication = ApiKeyAuthentication() excludes = ('time_created', 'time_modified') include_resource_uri = False dehydrate_village = partial(foreign_key_to_id, field_name='village', sub_field_names=['id']) hydrate_village = partial(dict_to_foreign_uri, field_name='village') def obj_create(self, bundle, request=None, **kwargs): village = Village.objects.get(id=bundle.data["village"]["online_id"]) attempt = Farmer.objects.filter(phone=bundle.data['phone'], name=bundle.data['name'], village=village) if attempt.count() < 1: bundle = super(FarmerResource, self).obj_create(bundle, **kwargs) else: send_duplicate_message(int(attempt[0].id)) return bundle def obj_update(self, bundle, request=None, **kwargs): try: bundle = super(FarmerResource, self).obj_update(bundle, **kwargs) except Exception, e: village = Village.objects.get( id=bundle.data["village"]["online_id"]) attempt = Farmer.objects.filter(phone=bundle.data['phone'], name=bundle.data['name'], village=village) send_duplicate_message(int(attempt[0].id)) return bundle
class PcapResource(MongoDBResource): id = fields.CharField(attribute="_id") analysis_id = fields.CharField(attribute="analysis_id") type = fields.CharField(attribute="type", null=True) sample_file = fields.FileField(attribute="pcap_file", null=True) class Meta: resource_name = 'pcap' authentication = ApiKeyAuthentication() object_class = Document collection = "pcaps" detail_uri_name = "_id" filtering = { 'analysis_id': ['exact'], } def prepend_urls(self): return [ #url to download file. url(r"^(?P<resource_name>%s)/(?P<pk>\w+)/file/$" % self._meta.resource_name, self.wrap_view('get_file'), name="api_get_file"), ] def dehydrate_sample_file(self, bundle): return '/api/v1/%s/%s/file/' % (self._meta.resource_name, bundle.obj.sample_id) def get_file(self, request, **kwargs): # Database MongoClient dbfs = MongoClient().thugfs fs = GridFS(dbfs) try: download_file = base64.b64decode( fs.get(ObjectId(kwargs['pk'])).read()) except: raise Http404("File not found") return HttpResponse(download_file, content_type='application/vnd.tcpdump.pcap')
class GigFileResource(ModelResource): gig = fields.ForeignKey(GigResource, 'gig_id') file = fields.FileField(attribute='file') class Meta: queryset = GigFile.objects.all() resource_name = 'gig_file' authorization = Authorization() limit = 0 def dispatch(self, request_type, request, **kwargs): return super().dispatch(request_type, request, **kwargs) def hydrate_gig(self, bundle): bundle.data['gig'] = MyUser.objects.get(id=bundle.data['gig']) return bundle def hydrate_file(self, bundle): bundle.data['file'] = bundle.request.FILES.get('file') return bundle
class ImageAttachResource(CommonModelResource): image = fields.FileField(attribute='image', null=True) image_thumbnail_1x = SorlThumbnailField( attribute='image', thumb_options={'geometry': '280x280'}, readonly=True) image_thumbnail_2x = SorlThumbnailField( attribute='image', thumb_options={'geometry': '800x800'}, readonly=True) image_thumbnail_3x = SorlThumbnailField( attribute='image', thumb_options={'geometry': '1024x1024'}, readonly=True) def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/(?P<pk>\d+)/set_image%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('set_image'), name="api_set_image"), ] def set_image(self, request=None, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) #self.throttle_check(request) if not request.user: return self.create_response( request, { 'error': 'You are anonymous user', }, HttpForbidden, ) request.FILES # Holy return super(ImageAttachResource, self).put_detail(request, **kwargs)