file_operation.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # coding=utf-8
  2. import os
  3. import requests
  4. from django.conf import settings
  5. from django.utils import timezone
  6. from django.utils.deconstruct import deconstructible
  7. def UploadFile(file, upload_path):
  8. upload_path = PathAndRename(upload_path)
  9. filename = "%s%s.%s" % (
  10. upload_path.path,
  11. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  12. file.name.split('.')[-1]
  13. )
  14. filename = filename.lower()
  15. full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
  16. with open(full_filename, 'wb+') as destination:
  17. for chunk in file.chunks():
  18. destination.write(chunk)
  19. return filename
  20. def DeleteFile(filename):
  21. img_path = '%s%s' % (settings.UIS_ROOT, filename)
  22. try:
  23. if os.path.exists(img_path):
  24. os.remove(img_path)
  25. except:
  26. import traceback
  27. traceback.print_exc()
  28. pass
  29. @deconstructible
  30. class PathAndRename(object):
  31. def __init__(self, sub_path):
  32. self.path = sub_path
  33. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  34. if not os.path.exists(self.full_path):
  35. os.makedirs(self.full_path)
  36. def __call__(self, instance, filename):
  37. ext = filename.split('.')[-1]
  38. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  39. if instance.pk:
  40. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  41. else:
  42. filename = '{}.{}'.format(t, ext)
  43. return os.path.join(self.path, filename)