def test_init(self): # Test that you have to use a dict some other resources with self.assertRaises(ValueError): GenericForeignKeyField(((Note, NoteResource)), 'nofield') # Test that you must register some other resources with self.assertRaises(ValueError): GenericForeignKeyField({}, 'nofield') # Test that the resources you raise must be models with self.assertRaises(ValueError): GenericForeignKeyField({NoteResource: Note}, 'nofield')
class PostResource(ModelResource): author = GenericForeignKeyField({ User: UserResource, }, 'author') last_modified_by = GenericForeignKeyField({ User: UserResource, }, 'last_modified_by') class Meta: queryset = Posts.objects.all() resource_name = 'post' authentication = ApiKeyAuthentication() authorization = DjangoAuthorization()
def test_resource_from_uri(self): note_2 = Note.objects.create(title='Generic and such', content='Sometimes it is to lorem ipsum') gfk_field = GenericForeignKeyField( { Note: NoteResource, Quote: QuoteResource }, 'nofield') self.assertEqual( gfk_field.resource_from_uri(gfk_field.to_class(), '/api/v1/notes/%s/' % note_2.pk).obj, note_2)
class ObjectACLResource(MyTardisModelResource): content_object = GenericForeignKeyField( { Experiment: ExperimentResource, # ... }, 'content_object') class Meta: authentication = default_authentication authorization = ACLAuthorization() queryset = ObjectACL.objects.all() filtering = { 'pluginId': ('exact', ), 'entityId': ('exact', ), } def hydrate(self, bundle): # Fill in the content type. if bundle.data['content_type'] == 'experiment': experiment = Experiment.objects.get(pk=bundle.data['object_id']) bundle.obj.content_type = experiment.get_ct() else: raise NotImplementedError(str(bundle.obj)) return bundle
class PlaylistItemResource(ModelResource): co_to = { Release: ReleaseResource, #Media: MediaResource, Media: SimpleMediaResource, Jingle: JingleResource, } content_object = GenericForeignKeyField(to=co_to, attribute='content_object', null=False, full=True) class Meta: queryset = PlaylistItem.objects.all() excludes = [ 'id', ] def dehydrate(self, bundle): bundle.data[ 'content_type'] = '%s' % bundle.obj.content_object.__class__.__name__.lower( ) bundle.data[ 'resource_uri'] = '%s' % bundle.obj.content_object.get_api_url() return bundle
class RatingResource(ModelResource): post = GenericForeignKeyField({ BlogProxy: PostResource, BlogPost: BlogPostResource, Recipe: RecipeResource }, 'content_object') class Meta: queryset = Rating.objects.all() resource_name = "rating" fields = ['id', 'object_pk', 'value',] list_allowed_methods = ['get', 'post',] detail_allowed_methods = ['get',] throttle = CacheDBThrottle() filtering = { 'object_pk': ('exact',), } serializer = CamelCaseJSONSerializer() authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() def alter_list_data_to_serialize(self, request, data): data['ratings'] = data['objects'] del data['objects'] return data def alter_deserialized_list_data(self, request, data): data['objects'] = data['ratings'] del data['ratings'] return data
class BanyanUserNotificationsResource(ModelResource): user = fields.ForeignKey('accounts.api.BanyanUserResource', 'user') from_user = fields.ForeignKey('accounts.api.BanyanUserResource', 'from_user', null=True, blank=True) content_object = GenericForeignKeyField( { Story: StoryResource, Piece: PieceResource, BanyanUser: BanyanUserResource, }, 'content_object', null=True, blank=True) class Meta: queryset = BanyanUserNotifications.objects.all() resource_name = 'notifications' list_allowed_methods = [] detail_allowed_methods = ['get'] authentication = ApiKeyAuthentication() #Only from the devices authorization = BanyanUserNotificationsAuthorization() filtering = { 'user': ALL_WITH_RELATIONS, }
class ActivityResource(ModelResource): user = fields.ForeignKey(BanyanUserResource, 'user', full=True) content_object = GenericForeignKeyField( { Story: StoryResource, Piece: PieceResource, BanyanUser: BanyanUserResource, }, 'content_object') class Meta: always_return_data = True queryset = Activity.objects.all() authentication = MultiAuthentication(ApiKeyAuthentication(), SessionAuthentication(), Authentication()) authorization = ActivityAuthorization() filtering = { 'object_id': ALL_WITH_RELATIONS, 'content_type': ALL_WITH_RELATIONS, 'user': ALL_WITH_RELATIONS, 'type': ['exact'] } def hydrate_user(self, bundle): if bundle.request.user.is_authenticated(): bundle.data['user'] = bundle.request.user return bundle
class ActionResource(ModelResource): """ API resource for accessing action profiles (script and dialogue). """ action_type = fields.ForeignKey(ActionTypeResource, 'action_type', null=True) related_item = fields.ForeignKey(ItemResource, 'related_item', null=True) content_object = GenericForeignKeyField( { DefaultActionSet: DefaultActionSetResource, Item: ItemResource, ItemCombo: ItemComboResource, Layer: LayerResource, TreeTopic: TreeTopicResource, }, 'content_object') class Meta: resource_name = 'action' queryset = Action.objects.all() always_return_data = True authorization = DjangoAuthorization() filtering = { 'id': ALL, 'content_object': ALL, 'content_type': ['exact'], 'object_id': ['exact'], }
class AssignedKeywordResource(ModelResource): assignments = fields.ToOneField('mezzanine_recipes.api.KeywordResource', 'keyword', full=True) post = GenericForeignKeyField({ BlogProxy: PostResource, BlogPost: BlogPostResource, Recipe: RecipeResource }, 'content_object') class Meta: queryset = AssignedKeyword.objects.all() resource_name = "assigned_keywords" fields = ['id', 'object_pk', '_order',] list_allowed_methods = ['get',] detail_allowed_methods = ['get',] throttle = CacheDBThrottle() filtering = { 'object_pk': ('exact',), } serializer = CamelCaseJSONSerializer() authentication = ApiKeyAuthentication() authorization = ReadOnlyAuthorization() def alter_list_data_to_serialize(self, request, data): data['assignedKeywords'] = data['objects'] del data['objects'] return data def alter_deserialized_list_data(self, request, data): data['objects'] = data['assignedKeywords'] del data['assignedKeywords'] return data
class LikeResource(CommonModelResource, AutoAssignCreatedByMixinResource): CREATED_BY_FIELD = 'src' created_by = fields.ForeignKey(UserReferenceResource, CREATED_BY_FIELD, use_in='detail') #delete parent field src = fields.ForeignKey(UserReferenceResource, CREATED_BY_FIELD, full=True, readonly=True) dst = fields.ForeignKey(CommonResource, 'dst') get_dst = GenericForeignKeyField( { CommonModel: CommonModelResource, CommonGoal: CommonGoalResource, Update: UpdateResource # Inspiration: InspirationResource # IN THE FUTURE }, 'get_dst', readonly=True, full=False) class Meta: queryset = Like.objects.all() resource_name = 'like' authentication = CommonApiKeyAuthentication() filtering = {'dst': ALL_WITH_RELATIONS, 'id': ALL} ordering = ['id']
class PlaylistItemResource(ModelResource): #media = fields.ToOneField('alibrary.api.MediaResource', 'media', null=True, full=True) co_to = { Release: ReleaseResource, #Media: MediaResource, Media: SimpleMediaResource, Jingle: JingleResource, } content_object = GenericForeignKeyField(to=co_to, attribute='content_object', null=False, full=True) class Meta: queryset = PlaylistItem.objects.all() #resource_name = 'playlistitem' excludes = [ 'id', ] def dehydrate(self, bundle): bundle.data[ 'content_type'] = '%s' % bundle.obj.content_object.__class__.__name__.lower( ) return bundle
class CommentResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') content_object = GenericForeignKeyField( { Bookmark: BookmarkResource, #List: ListResource }, 'content_object') class Meta: model = Comment queryset = Comment.objects.all() allowed_methods = ['get', 'post', 'delete'] always_return_data = True authentication = SessionAuthentication() authorization = CommentAuthorization() validation = FormValidation(form_class=CommentForm) filtering = {'object_pk': ALL} def dehydrate(self, bundle): user = bundle.obj.user bundle.data['avatar'] = avatar(user.email, 32) bundle.data['user_name'] = user.username bundle.data['submit_date'] = humanize.naturaltime( bundle.data['submit_date']) return bundle
def test_resource_from_uri(self): note_2 = Note.objects.create( title='Generic and such', content='Sometimes it is to lorem ipsum' ) gfk_field = GenericForeignKeyField({ Note: NoteResource, Quote: QuoteResource }, 'nofield') self.assertEqual( gfk_field.resource_from_uri( gfk_field.to_class(), '/api/v1/notes/%s/' % note_2.pk ).obj, note_2 )
def test_build_related_resource(self): gfk_field = GenericForeignKeyField( { Note: NoteResource, Quote: QuoteResource }, 'nofield') quote_1 = Quote.objects.create( byline='Issac Kelly', content='To ipsum or not to ipsum, that is the cliche') qr = QuoteResource() qr.build_bundle(obj=quote_1) bundle = gfk_field.build_related_resource('/api/v1/quotes/%s/' % quote_1.pk) # Test that the GFK field builds the same as the QuoteResource self.assertEqual(bundle.obj, quote_1)
class RatingResource(ModelResource): content_object = GenericForeignKeyField({ Note: NoteResource, Quote: QuoteResource }, 'content_object') class Meta: resource_name = 'ratings' queryset = Rating.objects.all()
def test_resource_from_uri(self): note_2 = Note.objects.create(title='Generic and such', content='Sometimes it is to lorem ipsum') gfk_field = GenericForeignKeyField( { Note: NoteResource, Quote: QuoteResource }, 'nofield') request = MockRequest() request.GET = {'format': 'json'} request.method = 'GET' self.assertEqual( gfk_field.resource_from_uri(gfk_field.to_class(), '/api/v1/notes/%s/' % note_2.pk, request).obj, note_2)
class DetailResource(ModelResource): user = GenericForeignKeyField({ User: UserResource, }, 'user') class Meta: queryset = UserDetail.objects.all() resource_name = 'detail' authentication = ApiKeyAuthentication() authorization = DjangoAuthorization()
def test_build_related_resource(self): gfk_field = GenericForeignKeyField({ Note: NoteResource, Quote: QuoteResource }, 'nofield') quote_1 = Quote.objects.create( byline='Issac Kelly', content='To ipsum or not to ipsum, that is the cliche' ) qr = QuoteResource() qr.build_bundle(obj=quote_1) bundle = gfk_field.build_related_resource( '/api/v1/quotes/%s/' % quote_1.pk ) # Test that the GFK field builds the same as the QuoteResource self.assertEqual(bundle.obj, quote_1)
class MeterReadResource(ModelResource): content_object = GenericForeignKeyField({ Meter: MeterResource, }, 'content_object') class Meta: queryset = MeterRead.objects.all() allowed_methods = ['get', 'post', 'patch'] authentication = BasicAuthentication() authorization = DjangoAuthorization()
class CommentResource(ModelResource): replied_to = fields.ToOneField('mezzanine_recipes.api.CommentResource', 'replied_to', null=True) content_object = GenericForeignKeyField( { BlogProxy: PostResource, BlogPost: BlogPostResource, Recipe: RecipeResource }, 'content_object') class Meta: queryset = ThreadedComment.objects.visible() resource_name = "comments" fields = [ 'id', 'object_pk', 'comment', 'submit_date', 'user_name', 'user_email', 'user_url', 'replied_to', ] list_allowed_methods = [ 'get', 'post', ] detail_allowed_methods = [ 'get', ] throttle = CacheDBThrottle() filtering = { 'object_pk': ('exact', ), } serializer = CamelCaseJSONSerializer() authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() limit = 0 def dehydrate_user_email(self, bundle): return None def dehydrate_user_url(self, bundle): return None def alter_list_data_to_serialize(self, request, data): data['comments'] = data['objects'] del data['objects'] return data def alter_deserialized_list_data(self, request, data): data['objects'] = data['comments'] del data['comments'] return data
class FocusResource(BaseResource): content_object = GenericForeignKeyField( { Question: QuestionResource, Article: ArticleResource, Tag: TagResource, User: UserResource, }, 'content_object') def post_list(self, request, **kwargs): deserialized = self.deserialize(request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json')) deserialized = self.alter_deserialized_detail_data( request, deserialized) bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request) content_object = self.content_object.hydrate(bundle).obj obj = Focus.objects.filter( user=bundle.request.user, content_type=ContentType.objects.get_for_model(content_object), object_id=content_object.id) if obj.exists(): bundle = self.full_bundle(obj[0], bundle.request) super(FocusResource, self).obj_delete(bundle, **kwargs) return http.HttpNoContent() updated_bundle = self.obj_create( bundle, **self.remove_api_resource_names(kwargs)) location = self.get_resource_uri(updated_bundle) if not self._meta.always_return_data: return http.HttpCreated(location=location) else: updated_bundle = self.full_dehydrate(updated_bundle) updated_bundle = self.alter_detail_data_to_serialize( request, updated_bundle) return self.create_response(request, updated_bundle, response_class=http.HttpCreated, location=location) def obj_create(self, bundle, **kwargs): return super(FocusResource, self).obj_create(bundle, user=bundle.request.user) class Meta: queryset = Focus.objects.all() resource_name = 'focus' authentication = SessionAuthentication() authorization = DjangoAuthorization() list_allowed_methods = ['post'] detail_allowed_methods = [] always_return_data = True
class SearchResource(Resource): item = GenericForeignKeyField(RESOURCE_MAP, 'object', readonly=True, full=True, null=True) score = fields.FloatField(attribute='score', readonly=True, blank=True, null=True) class Meta: resource_name = 'search' object_class = SearchObject authentication = CommonApiKeyAuthentication() def get_object_list(self, request): # for case no search from haystack.inputs import AutoQuery from haystack.query import SearchQuerySet params = request.GET sqs = SearchQuerySet() if len(params.getlist('content_type')): for content_type in params.getlist('content_type'): sqs = sqs.models(get_model(*content_type.split('.'))) #if params.get('order_by'): # sqs = sqs.order_by(params.get('order_by', '')) if params.get('q', ''): sqs = sqs.filter_or(content=AutoQuery(params.get('q', '').lower())) for k, v in params.iteritems(): if k not in ['q', 'page', 'limit', 'content_type', 'order_by']: sqs = sqs.filter_or(**{k: v}) limit = int(request.GET.get('limit', 20)) page = int(request.GET.get('page', 1)) - 1 object_list = sqs[page * limit:(page * limit + limit)] objects = [] for result in object_list: objects.append(result) return objects def obj_get_list(self, bundle, **kwargs): # Filtering disabled for brevity... return self.get_object_list(bundle.request)
def test_get_related_resource(self): gfk_field = GenericForeignKeyField( { Note: NoteResource, Quote: QuoteResource }, 'nofield') definition_1 = Definition.objects.create( word='toast', content="Cook or brown (food, esp. bread or cheese)") # Test that you can not link to a model that does not have a resource with self.assertRaises(TypeError): gfk_field.get_related_resource(definition_1) note_1 = Note.objects.create( title='All aboard the rest train', content='Sometimes it is just better to lorem ipsum') self.assertTrue( isinstance(gfk_field.get_related_resource(note_1), NoteResource))
def test_get_related_resource(self): gfk_field = GenericForeignKeyField({ Note: NoteResource, Quote: QuoteResource }, 'nofield') definition_1 = Definition.objects.create( word='toast', content="Cook or brown (food, esp. bread or cheese)" ) # Test that you can not link to a model that does not have a resource with self.assertRaises(TypeError): gfk_field.get_related_resource(definition_1) note_1 = Note.objects.create( title='All aboard the rest train', content='Sometimes it is just better to lorem ipsum' ) self.assertTrue(isinstance(gfk_field.get_related_resource(note_1), NoteResource))
class HashTagged_ItemResource(ModelResource): user = fields.ForeignKey(UserResource, "user", full=True) content_object = GenericForeignKeyField( { HashTag: HashTagResource, User: UserResource }, 'content_object') class Meta: resource_name = 'hashtagged_item' queryset = HashTagged_Item.objects.all()
def test_resource_from_uri(self): note_2 = Note.objects.create( title='Generic and such', content='Sometimes it is to lorem ipsum' ) gfk_field = GenericForeignKeyField({ Note: NoteResource, Quote: QuoteResource }, 'nofield') request = MockRequest() request.GET = {'format': 'json'} request.method = 'GET' self.assertEqual( gfk_field.resource_from_uri( gfk_field.to_class(), '/api/v1/notes/%s/' % note_2.pk, request ).obj, note_2 )
class TimelineItemResource(ModelResource): # The GenericForeignKeyFields allows you to specify the related object # via its REST endpoint. Any support models need to be listed in the # dict passed to GenericForeignKeyField content_object = GenericForeignKeyField({ Event: EventResource, }, 'content_object') class Meta: queryset = TimelineItem.objects.filter(visible=True) resource_name = 'timeline-item' authorization = DjangoAuthorization() allowed_methods = ['post', 'get'] always_return_data = True
class ExportItemResource(ModelResource): export_session = fields.ForeignKey('exporter.api.ExportResource', 'export_session', null=True, full=False) co_to = { Release: ReleaseResource, Artist: ArtistResource, } content_object = GenericForeignKeyField(to=co_to, attribute='content_object', null=False, full=False) class Meta: queryset = ExportItem.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] resource_name = 'exportitem' # excludes = ['type','results_musicbrainz'] #excludes = ['id',] authentication = MultiAuthentication(SessionAuthentication(), ApiKeyAuthentication()) authorization = Authorization() always_return_data = True filtering = { 'import_session': ALL_WITH_RELATIONS, 'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'], } def apply_authorization_limits(self, request, object_list): return object_list.filter(export_session__user=request.user) def obj_create(self, bundle, request, **kwargs): item = bundle.data['item'] print bundle.data['item']['item_id'] # dummy if item['item_type'] == 'release': co = Release.objects.get(pk=int(item['item_id'])) bundle.data['content_object'] = co return super(ExportItemResource, self).obj_create(bundle, request, **kwargs)
class ResourceFileResource(ModelResource): content_object = GenericForeignKeyField( {GenericResource: GenericResourceResource}, 'content_object') class Meta: always_return_data = True queryset = ResourceFile.objects.all() resource_name = 'resource_file' filtering = { 'id': 'exact', } authentication = MultiAuthentication(BasicAuthentication(), ApiKeyAuthentication(), SessionAuthentication()) authorization = Authorization()
class DublinCoreResource(ModelResource): content_object = GenericForeignKeyField( {GenericResource: GenericResourceResource}, 'content_object') class Meta: always_return_data = True queryset = QualifiedDublinCoreElement.objects.all() resource_name = 'dublincore' filtering = { 'id': 'exact', } authentication = MultiAuthentication(BasicAuthentication(), ApiKeyAuthentication(), SessionAuthentication()) #authorization = HydroshareAuthorization() authorization = Authorization()
class ObjectACLAppResource(tardis.tardis_portal.api.ObjectACLResource): content_object = GenericForeignKeyField({ Experiment: tardis.tardis_portal.api.ExperimentResource, # ... }, 'content_object') class Meta(tardis.tardis_portal.api.ObjectACLResource.Meta): # This will be mapped to <app_name>_experiment by MyTardis's urls.py # (eg /api/v1/sequencing_facility_objectacl/) resource_name = 'objectacl' authorization = AppACLAuthorization() filtering = { 'pluginId': ('exact', ), 'entityId': ('exact', ), 'object_id': ('exact', ), 'content_type': ('exact', ), 'aclOwnershipType': ('exact', ), }
class InviteResource(BaseResource): recipient = fields.ForeignKey(UserResource, attribute='recipient') content_object = GenericForeignKeyField({Question: QuestionResource}, 'content_object') def hydrate_recipient(self, bundle): recipient = bundle.data['recipient'] try: if bundle.request.user.username == recipient: raise ApiFieldError("不能邀请自己") user = User.objects.get_by_natural_key(recipient) bundle.data['recipient'] = user except ObjectDoesNotExist: raise ApiFieldError("用户不存在") return bundle def save(self, bundle, skip_errors=False): obj = self.content_object.hydrate(bundle).obj if Invite.objects.filter( recipient=self.recipient.hydrate(bundle).obj, content_type=ContentType.objects.get_for_model(obj), object_id=obj.id).exists(): raise ApiFieldError("用户邀请") return super(InviteResource, self).save(bundle, skip_errors) def obj_create(self, bundle, **kwargs): return super(InviteResource, self).obj_create(bundle, sender=bundle.request.user) class Meta: queryset = Invite.objects.all() resource_name = 'invite' authentication = SessionAuthentication() authorization = DjangoAuthorization() list_allowed_methods = ['post'] detail_allowed_methods = [] always_return_data = True
class ContentHideResource(ModelResource): user = fields.ForeignKey('accounts.api.BanyanUserResource', 'user') content_object = GenericForeignKeyField( { Story: StoryResource, Piece: PieceResource, }, 'content_object') class Meta: resource_name = 'hide_object' queryset = HiddenObject.objects.all() authentication = MultiAuthentication(ApiKeyAuthentication(), SessionAuthentication()) authorization = Authorization() list_allowed_methods = ['post'] detail_allowed_methods = [] cache = SimpleCache() def hydrate_user(self, bundle): if bundle.request.user.is_authenticated(): bundle.data['user'] = bundle.request.user return bundle