file_operation.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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.UIS_ROOT, filename)
  36. try:
  37. if os.path.exists(img_path):
  38. os.remove(img_path)
  39. except:
  40. import traceback
  41. traceback.print_exc()
  42. pass
  43. @deconstructible
  44. class PathAndRename(object):
  45. def __init__(self, sub_path):
  46. self.path = sub_path
  47. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  48. if not os.path.exists(self.full_path):
  49. os.makedirs(self.full_path)
  50. def __call__(self, instance, filename):
  51. ext = filename.split('.')[-1]
  52. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  53. if instance.pk:
  54. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  55. else:
  56. filename = '{}.{}'.format(t, ext)
  57. return os.path.join(self.path, filename)
  58. @deconstructible
  59. class CertPath(object):
  60. def __init__(self, sub_path):
  61. self.path = sub_path
  62. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  63. if not os.path.exists(self.full_path):
  64. os.makedirs(self.full_path)
  65. def __call__(self, instance, filename):
  66. return os.path.join(self.path, filename)