file_operation.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 DownloadFace(url, save_path, ext):
  21. upload_path = PathAndRename(save_path)
  22. filename = "%s%s.%s" % (
  23. upload_path.path,
  24. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  25. ext
  26. )
  27. filename = filename.lower()
  28. full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
  29. response = requests.get(url)
  30. img = response.content
  31. with open(full_filename, 'wb+') as destination:
  32. destination.write(img)
  33. return filename
  34. def DeleteFile(filename):
  35. img_path = '%s/%s' % (settings.MEDIA_ROOT, filename)
  36. try:
  37. if os.path.exists(img_path):
  38. os.remove(img_path)
  39. except:
  40. pass
  41. @deconstructible
  42. class PathAndRename(object):
  43. def __init__(self, sub_path):
  44. self.path = sub_path
  45. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  46. if not os.path.exists(self.full_path):
  47. os.makedirs(self.full_path)
  48. def __call__(self, instance, filename):
  49. ext = filename.split('.')[-1]
  50. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  51. if instance.pk:
  52. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  53. else:
  54. filename = '{}.{}'.format(t, ext)
  55. return os.path.join(self.path, filename)