|
1 |
import datetime
|
1 |
2 |
import uuid
|
2 |
3 |
import collections
|
3 |
4 |
|
... | ... | |
16 |
17 |
from django.views.generic import View
|
17 |
18 |
|
18 |
19 |
from import_export.fields import Field
|
|
20 |
import tablib
|
19 |
21 |
|
20 |
22 |
from authentic2.constants import SWITCH_USER_SESSION_KEY
|
21 |
23 |
from authentic2.models import Attribute, PasswordReset
|
... | ... | |
321 |
323 |
resource_class = UserResource
|
322 |
324 |
export_prefix = 'users-'
|
323 |
325 |
|
324 |
|
def get_resource(self):
|
325 |
|
'''Subclass default UserResource class to dynamically add field for extra attributes'''
|
326 |
|
attrs = collections.OrderedDict()
|
327 |
|
for attribute in Attribute.objects.all():
|
328 |
|
attrs['attribute_%s' % attribute.name] = Field(attribute='attributes__%s' % attribute.name)
|
329 |
|
custom_class = type('UserResourceClass', (self.resource_class,), attrs)
|
330 |
|
return custom_class()
|
331 |
|
|
332 |
326 |
def get_queryset(self):
|
333 |
327 |
'''Prefetch attribute values.'''
|
334 |
328 |
qs = super(UsersExportView, self).get_queryset()
|
335 |
329 |
return qs.prefetch_related('attribute_values', 'attribute_values__attribute')
|
336 |
330 |
|
|
331 |
@property
|
|
332 |
def csv(self):
|
|
333 |
return self._dataset.export('csv')
|
|
334 |
|
|
335 |
def get_dataset(self):
|
|
336 |
user_resource = UserResource()
|
|
337 |
fields = user_resource._meta.export_order + ('email_verified', 'is_active', 'modified')
|
|
338 |
attributes = [attr.name for attr in Attribute.objects.all()]
|
|
339 |
headers = fields + tuple(['attribute_%s' % attr for attr in attributes])
|
|
340 |
|
|
341 |
def iso(rec):
|
|
342 |
if hasattr(rec, 'strftime'):
|
|
343 |
if isinstance(rec, datetime.datetime):
|
|
344 |
_format = "%Y-%m-%d %H:%M:%S"
|
|
345 |
else:
|
|
346 |
_format = "%Y-%m-%d"
|
|
347 |
return rec.strftime(_format)
|
|
348 |
return rec
|
|
349 |
|
|
350 |
def create_record(user):
|
|
351 |
record = []
|
|
352 |
for field in fields:
|
|
353 |
if field == 'roles':
|
|
354 |
value = user_resource.dehydrate_roles(user)
|
|
355 |
else:
|
|
356 |
value = getattr(user, field)
|
|
357 |
record.append(value)
|
|
358 |
|
|
359 |
attr_d = user.attributes.values
|
|
360 |
for attr in attributes:
|
|
361 |
record.append(attr_d.get(attr, ''))
|
|
362 |
|
|
363 |
return map(iso, record)
|
|
364 |
|
|
365 |
self._dataset = tablib.Dataset(headers=headers)
|
|
366 |
for user in self.get_data():
|
|
367 |
self._dataset.append(create_record(user))
|
|
368 |
return self
|
|
369 |
|
|
370 |
|
337 |
371 |
users_export = UsersExportView.as_view()
|
338 |
372 |
|
339 |
373 |
|
340 |
|
-
|