Skip to content

Instantly share code, notes, and snippets.

@fhdez
Created August 1, 2018 23:09
Show Gist options
  • Save fhdez/3dfe4902e60447499605fc0239730436 to your computer and use it in GitHub Desktop.
Save fhdez/3dfe4902e60447499605fc0239730436 to your computer and use it in GitHub Desktop.
class ActivityRecordViewSet(GenericViewSet):
@detail_route(
methods=['GET'],
permission_classes=[DirectorPermission])
def csv(self, request, pk, *args, **kwargs):
"""
Download a report of a domain complete or period
---
omit_serializer: true
responseMessages:
- code: 200
message: OK
- code: 403
message: FORBIDDEN
- code: 404
message: NOT FOUND
- code: 500
message: INTERNAL SERVER ERROR
consumes:
- application/json
produces:
- application/json
"""
date_since = request.GET.get('datesince', None)
date_to = request.GET.get('dateto', None)
verbs = request.GET.get(
'verb', settings.CUSTOM_ACTIONS.values()
)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="logs.csv"'
response['x-filename'] = "logs.csv"
domain = Domain.objects.get(pk=pk)
writer = csv.writer(response)
writer.writerow(['usuario', 'acción', 'modelo', 'fecha'])
content_type = ContentType.objects.get(model="user", app_label="users")
if type(verbs) is unicode:
verbs = [verbs]
users = map(
str,
User.objects.filter(
email__contains=domain.name
).values_list(
'id',
flat=True
)
)
queryset = Action.objects.filter(
actor_content_type_id=content_type.id,
actor_object_id__in=users,
verb__in=verbs
)
# Search for a date specific
if date_since or date_to:
# Search for a range of date
if date_since and date_to:
date_ini = datetime.datetime.strptime(date_since, "%Y-%m-%d")
date_end = datetime.datetime.strptime(date_to, "%Y-%m-%d")
date_end += datetime.timedelta(days=1)
queryset = Action.objects.filter(
actor_content_type_id=content_type.id,
actor_object_id__in=users,
verb__in=verbs,
timestamp__range=(date_ini, date_end)
)
# Search for since date
if date_since and not date_to:
date = datetime.datetime.strptime(date_since, "%Y-%m-%d")
queryset = Action.objects.filter(
actor_content_type_id=content_type.id,
actor_object_id__in=users,
verb__in=verbs,
timestamp__gt=(date)
)
# Search for to date
if date_to and not date_since:
date = datetime.datetime.strptime(date_to, "%Y-%m-%d")
date += datetime.timedelta(days=1)
queryset = Action.objects.filter(
actor_content_type_id=content_type.id,
actor_object_id__in=users,
verb__in=verbs,
timestamp__lt=(date)
)
serializer = serializers.ActivitySerializer(queryset, many=True)
for data in serializer.data:
row = [
data['actor']['email'],
data['verb'],
data['target'],
data['timestamp'],
]
writer.writerow(row)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment