123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- # coding=utf-8
- import os
- 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 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)
|