file_operation.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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.MEDIA_ROOT, filename)
  22. try:
  23. if os.path.exists(img_path):
  24. os.remove(img_path)
  25. except:
  26. pass
  27. @deconstructible
  28. class PathAndRename(object):
  29. def __init__(self, sub_path):
  30. self.path = sub_path
  31. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  32. if not os.path.exists(self.full_path):
  33. os.makedirs(self.full_path)
  34. def __call__(self, instance, filename):
  35. ext = filename.split('.')[-1]
  36. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  37. if instance.pk:
  38. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  39. else:
  40. filename = '{}.{}'.format(t, ext)
  41. return os.path.join(self.path, filename)