def pack(cls, instances, **kwargs): requester = kwargs.get('requester') path = os.path.join(tempfile.gettempdir(), 'test.txt') with open(path, 'w') as f: f.write('test') return add_attachment_from_disk(instances, path, requester, 'pack action')
def _generate_report(cls, name, requester, instances, language): report = Report.objects.get(name=name) template = report.templates.filter(language=language).first() if not template: template = report.templates.filter(default=True).first() template_content = '' with open(template.template.path, 'rb') as f: template_content = f.read() data_instances = [{ 'sn': obj.sn, 'model': str(obj.model), 'imei': obj.imei, 'imei2': obj.imei2, 'barcode': obj.barcode, } for obj in instances] service_pdf = ExternalService('PDF') result = service_pdf.run(template=template_content, data={ 'id': ', '.join( [str(obj.id) for obj in instances]), 'now': datetime.datetime.now(), 'logged_user': obj_to_dict(requester), 'affected_user': obj_to_dict(instances[0].user), 'owner': obj_to_dict(instances[0].owner), 'assets': data_instances, }) filename = "_".join([ timezone.now().isoformat()[:10], instances[0].user.get_full_name().lower().replace(' ', '-'), name, ]) + '.pdf' with tempfile.TemporaryDirectory() as tmp_dirpath: output_path = os.path.join(tmp_dirpath, filename) with open(output_path, 'wb') as f: f.write(result) return add_attachment_from_disk( instances, output_path, requester, _('Document autogenerated by {} transition.').format(name))
def save_attachments(self, directory): with open(os.path.join(directory, 'attachments.csv')) as f: reader = csv.reader(f, delimiter=',') csv_data = list(reader) headers, csv_body = csv_data[0], csv_data[1:] dataset = tablib.Dataset(*csv_body, headers=headers) for line in dataset.dict: model = MODELS_MAP.get(line.get('parent_type'), None) if model: try: obj = ImportedObjects.get_object_from_old_pk( model, line.get('parents')) except ImportedObjectDoesNotExist: logger.warning( 'Missing imported object for {}'.format(line)) continue if line.get('md5'): owner, _ = get_user_model().objects.get_or_create( username=line.get('uploaded_by')) try: attachment = Attachment.objects.get( md5=line.get('md5')) content_type = ContentType.objects.get_for_model( obj._meta.model) items = attachment.items.filter( object_id=obj.pk, content_type=content_type) if not items: AttachmentItem.objects.attach( obj.pk, content_type, [attachment]) continue except Attachment.DoesNotExist: pass attachment = add_attachment_from_disk( obj, os.path.join(directory, 'attachments', line.get('file')), owner=owner) attachment.original_filename = line.get( 'original_filename') attachment.save(update_fields=['original_filename'])
def save_transition_history(self, directory): with open(os.path.join(directory, 'transition_history.csv')) as f: reader = csv.reader(f, delimiter=',') csv_data = list(reader) headers, csv_body = csv_data[0], csv_data[1:] dataset = tablib.Dataset(*csv_body, headers=headers) for line in dataset.dict: model = MODELS_MAP.get(line.get('asset_type')) try: obj = ImportedObjects.get_object_from_old_pk( model, line.get('asset')) except ImportedObjectDoesNotExist: logger.warning('Missing imported object for %s', line) continue logged_user, _ = get_user_model().objects.get_or_create( username=line.get('logged_user')) new_history = False old_history_id = '{}|{}'.format(line.get('id'), line.get('asset')) try: history = ImportedObjects.get_object_from_old_pk( TransitionsHistory, old_history_id) except ImportedObjectDoesNotExist: history = TransitionsHistory() new_history = True history.content_type = ContentType.objects.get_for_model(model) history.created = line.get('created') history.modified = line.get('modified') history.logged_user = logged_user history.transition_name = line.get('transition') history.kwargs = json.loads(line.get('kwargs', {})) actions = [ i.replace('_', ' ').capitalize() for i in line.get('actions').split(',') ] history.actions = actions history.object_id = obj.pk if line.get('report_filename_md5'): try: history.attachment = Attachment.objects.get( md5=line.get('report_filename_md5')) except Attachment.DoesNotExist: try: attachment = add_attachment_from_disk( obj, os.path.join(directory, 'transition_history', 'assets', line.get('report_filename')), owner=logged_user) history.attachment = attachment except FileNotFoundError: pass history.save() # update history record using update method to skip auto_now # and auto_now_add fields checks TransitionsHistory.objects.filter(pk=history.pk).update( created=line.get('created'), modified=line.get('modified'), ) if new_history: ImportedObjects.create(history, old_history_id)