Skip to content

Commit

Permalink
Merge pull request #657 from onaio/add-active
Browse files Browse the repository at this point in the history
Use decorator to check for object in serializers
  • Loading branch information
pld committed Nov 3, 2014
2 parents e5b2043 + 415e8a0 commit 211da1c
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 57 deletions.
4 changes: 3 additions & 1 deletion onadata/apps/api/tests/viewsets/test_xform_viewset.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,14 +404,16 @@ def test_partial_update(self):
})
title = u'مرحب'
description = 'DESCRIPTION'
data = {'public': True, 'description': description, 'title': title}
data = {'public': True, 'description': description, 'title': title,
'downloadable': True}

self.assertFalse(self.xform.shared)

request = self.factory.patch('/', data=data, **self.extra)
response = view(request, pk=self.xform.id)

self.xform.reload()
self.assertTrue(self.xform.downloadable)
self.assertTrue(self.xform.shared)
self.assertEqual(self.xform.description, description)
self.assertEqual(response.data['public'], True)
Expand Down
8 changes: 4 additions & 4 deletions onadata/apps/api/viewsets/xform_viewset.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,9 @@ class XFormViewSet(AnonymousUserPublicFormsMixin, LabelsMixin, ModelViewSet):
## Set Form Information
You can use `PUT` or `PATCH` http methods to update or set form data elements.
If you are using `PUT`, you have to provide the `uuid, description, owner,
public, public_data` fields. With `PATCH` you only need provide atleast one
of the fields.
If you are using `PUT`, you have to provide the `uuid, description,
downloadable, owner, public, public_data, title` fields. With `PATCH` you only
need provide at least one of the fields.
<pre class="prettyprint">
<b>PATCH</b> /api/v1/forms/<code>{pk}</code></pre>
Expand Down Expand Up @@ -600,7 +600,7 @@ class XFormViewSet(AnonymousUserPublicFormsMixin, LabelsMixin, ModelViewSet):
lookup_field = 'pk'
extra_lookup_fields = None
permission_classes = [XFormPermissions, ]
updatable_fields = set(('description', 'require_auth',
updatable_fields = set(('description', 'downloadable', 'require_auth',
'shared', 'shared_data', 'title'))
filter_backends = (filters.AnonDjangoObjectPermissionFilter,
filters.TagFilter,
Expand Down
5 changes: 3 additions & 2 deletions onadata/libs/serializers/attachment_serializer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from rest_framework import serializers
from onadata.apps.logger.models.attachment import Attachment
from onadata.libs.utils.decorators import check_obj
from onadata.libs.utils.image_tools import image_url


Expand All @@ -21,9 +22,9 @@ class Meta:
lookup_field = 'pk'
model = Attachment

@check_obj
def get_download_url(self, obj):
if obj is not None:
return obj.media_file.url if obj.media_file.url else None
return obj.media_file.url if obj.media_file.url else None

def get_small_download_url(self, obj):
if obj.mimetype.startswith('image'):
Expand Down
33 changes: 17 additions & 16 deletions onadata/libs/serializers/project_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
from rest_framework import serializers

from onadata.apps.api.models import Project
from onadata.apps.logger.models import Instance
from onadata.libs.permissions import get_object_users_with_permissions
from onadata.libs.serializers.fields.boolean_field import BooleanField
from onadata.libs.serializers.fields.json_field import JsonField
from onadata.libs.serializers.tag_list_serializer import TagListSerializer
from onadata.apps.logger.models import Instance
from onadata.libs.utils.decorators import check_obj


class ProjectSerializer(serializers.HyperlinkedModelSerializer):
Expand Down Expand Up @@ -65,35 +66,35 @@ def restore_object(self, attrs, instance=None):
def get_project_permissions(self, obj):
return get_object_users_with_permissions(obj)

@check_obj
def get_project_forms(self, obj):
if obj is not None:
xforms_details = obj.projectxform_set.values(
'xform__pk', 'xform__title')
return [{'name': form['xform__title'], 'id':form['xform__pk']}
for form in xforms_details]
xforms_details = obj.projectxform_set.values(
'xform__pk', 'xform__title')
return [{'name': form['xform__title'], 'id':form['xform__pk']}
for form in xforms_details]

@check_obj
def get_num_datasets(self, obj):
"""Return the number of datasets attached to the object.
:param obj: The project to find datasets for.
"""
if obj:
return obj.projectxform_set.count()
return obj.projectxform_set.count()

@check_obj
def get_last_submission_date(self, obj):
"""Return the most recent submission date to any of the projects
datasets.
:param obj: The project to find the last submission date for.
"""
if obj:
xform_ids = obj.projectxform_set.values_list('xform', flat=True)
last_submission = Instance.objects.\
order_by('-date_created').\
filter(xform_id__in=xform_ids).values_list('date_created',
flat=True)

return last_submission and last_submission[0]
xform_ids = obj.projectxform_set.values_list('xform', flat=True)
last_submission = Instance.objects.\
order_by('-date_created').\
filter(xform_id__in=xform_ids).values_list('date_created',
flat=True)

return last_submission and last_submission[0]

def is_starred_project(self, obj):
request = self.context['request']
Expand Down
66 changes: 32 additions & 34 deletions onadata/libs/serializers/xform_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,26 @@
from onadata.libs.serializers.fields.boolean_field import BooleanField
from onadata.libs.serializers.tag_list_serializer import TagListSerializer
from onadata.libs.serializers.metadata_serializer import MetaDataSerializer
from onadata.libs.utils.decorators import check_obj


class XFormSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='xform-detail',
lookup_field='pk')
formid = serializers.Field(source='id')
metadata = serializers.SerializerMethodField('get_xform_metadata')
owner = serializers.HyperlinkedRelatedField(view_name='user-detail',
source='user',
lookup_field='username')
public = BooleanField(source='shared', widget=widgets.CheckboxInput())
public_data = BooleanField(source='shared_data')
require_auth = BooleanField(source='require_auth',
widget=widgets.CheckboxInput())
submission_count_for_today = serializers.Field(
source='submission_count_for_today')
title = serializers.CharField(max_length=255, source='title')
owner = serializers.HyperlinkedRelatedField(
view_name='user-detail',
source='user', lookup_field='username')
public = BooleanField(
source='shared', widget=widgets.CheckboxInput())
public_data = BooleanField(
source='shared_data')
require_auth = BooleanField(
source='require_auth', widget=widgets.CheckboxInput())
tags = TagListSerializer(read_only=True)
title = serializers.CharField(max_length=255, source='title')
url = serializers.HyperlinkedIdentityField(view_name='xform-detail',
lookup_field='pk')
users = serializers.SerializerMethodField('get_xform_permissions')
metadata = serializers.SerializerMethodField('get_xform_metadata')

class Meta:
model = XForm
Expand Down Expand Up @@ -61,42 +60,41 @@ class XFormListSerializer(serializers.Serializer):
def get_version(self, obj):
return None

@check_obj
def get_hash(self, obj):
if obj:
return u"md5:%s" % obj.hash
return u"md5:%s" % obj.hash

@check_obj
def get_url(self, obj):
if obj:
kwargs = {'pk': obj.pk, 'username': obj.user.username}
request = self.context.get('request')
kwargs = {'pk': obj.pk, 'username': obj.user.username}
request = self.context.get('request')

return reverse('download_xform', kwargs=kwargs,
request=request)
return reverse('download_xform', kwargs=kwargs, request=request)

@check_obj
def get_manifest_url(self, obj):
if obj:
kwargs = {'pk': obj.pk, 'username': obj.user.username}
request = self.context.get('request')
kwargs = {'pk': obj.pk, 'username': obj.user.username}
request = self.context.get('request')

return reverse('manifest-url', kwargs=kwargs,
request=request)
return reverse('manifest-url', kwargs=kwargs, request=request)


class XFormManifestSerializer(serializers.Serializer):
filename = serializers.Field(source='data_value')
hash = serializers.SerializerMethodField('get_hash')
downloadUrl = serializers.SerializerMethodField('get_url')

@check_obj
def get_url(self, obj):
if obj:
kwargs = {'pk': obj.xform.pk, 'username': obj.xform.user.username,
'metadata': obj.pk}
request = self.context.get('request')
format = obj.data_value[obj.data_value.rindex('.') + 1:]
kwargs = {'pk': obj.xform.pk,
'username': obj.xform.user.username,
'metadata': obj.pk}
request = self.context.get('request')
format = obj.data_value[obj.data_value.rindex('.') + 1:]

return reverse('xform-media', kwargs=kwargs,
request=request, format=format.lower())
return reverse('xform-media', kwargs=kwargs,
request=request, format=format.lower())

@check_obj
def get_hash(self, obj):
if obj:
return u"%s" % (obj.file_hash or 'md5:')
return u"%s" % (obj.file_hash or 'md5:')
9 changes: 9 additions & 0 deletions onadata/libs/utils/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
from onadata.apps.logger.models import XForm


def check_obj(f):
@wraps(f)
def with_check_obj(*args, **kwargs):
if args[0]:
return f(*args, **kwargs)

return with_check_obj


def is_owner(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
Expand Down

0 comments on commit 211da1c

Please sign in to comment.