# coding=utf-8 import os import time import requests from django.conf import settings from django.utils import timezone from django.utils.deconstruct import deconstructible def UploadFile(file, upload_path): upload_path = PathAndRename(upload_path) filename = "%s%s.%s" % ( upload_path.path, timezone.now().strftime('%Y%m%d%H%M%S%f'), file.name.split('.')[-1] ) filename = filename.lower() full_filename = "%s%s" % (settings.MEDIA_ROOT, filename) with open(full_filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) return filename def DownloadFace(url, save_path, ext): upload_path = PathAndRename(save_path) filename = "%s%s.%s" % ( upload_path.path, timezone.now().strftime('%Y%m%d%H%M%S%f'), ext ) filename = filename.lower() full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename) response = requests.get(url) img = response.content with open(full_filename, 'wb+') as destination: destination.write(img) return filename def DeleteFile(filename): img_path = '%s%s' % (settings.UIS_ROOT, filename) try: if os.path.exists(img_path): os.remove(img_path) except: import traceback traceback.print_exc() pass @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path) if not os.path.exists(self.full_path): os.makedirs(self.full_path) def __call__(self, instance, filename): ext = filename.split('.')[-1] t = timezone.now().strftime('%Y%m%d%H%M%S%f') if instance.pk: filename = '{}-{}.{}'.format(instance.pk, t, ext) else: filename = '{}.{}'.format(t, ext) return os.path.join(self.path, filename) @deconstructible class CertPath(object): def __init__(self, sub_path): self.path = sub_path self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path) if not os.path.exists(self.full_path): os.makedirs(self.full_path) def __call__(self, instance, filename): return os.path.join(self.path, filename) def attachment_save(export_data, name): now = int(time.time()) # 删除过期文件 # files = os.listdir(settings.EXPORT_ROOT) # for file in files: # filePath = os.path.join(settings.EXPORT_ROOT, file) # # print(11111111111, filePath) # if os.path.isfile(filePath): # last = int(os.stat(filePath).st_atime) # if now - last > 180: # os.remove(filePath) # print(filePath + " was removed!") filename = '{}.xlsx'.format(name) full_filename = os.path.join(settings.EXPORT_ROOT, filename) open(full_filename, 'wb').write(getattr(export_data, 'xlsx')) return settings.EXPORT_URL + filename