file_operation.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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, user_id):
  8. upload_path = PathAndRename(upload_path)
  9. filename = "%s%s_%s.%s" % (
  10. upload_path.path,
  11. user_id,
  12. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  13. file.name.split('.')[-1]
  14. )
  15. filename = filename.lower()
  16. full_filename = "%s%s" % (settings.MEDIA_ROOT, filename)
  17. with open(full_filename, 'wb+') as destination:
  18. for chunk in file.chunks():
  19. destination.write(chunk)
  20. return filename
  21. def DownloadFace(url, save_path, ext):
  22. upload_path = PathAndRename(save_path)
  23. filename = "%s%s.%s" % (
  24. upload_path.path,
  25. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  26. ext
  27. )
  28. filename = filename.lower()
  29. full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
  30. response = requests.get(url)
  31. img = response.content
  32. with open(full_filename, 'wb+') as destination:
  33. destination.write(img)
  34. return filename
  35. def DeleteFile(filename):
  36. img_path = '%s%s' % (settings.UIS_ROOT, filename)
  37. try:
  38. if os.path.exists(img_path):
  39. os.remove(img_path)
  40. except:
  41. import traceback
  42. traceback.print_exc()
  43. pass
  44. @deconstructible
  45. class PathAndRename(object):
  46. def __init__(self, sub_path):
  47. self.path = sub_path
  48. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  49. if not os.path.exists(self.full_path):
  50. os.makedirs(self.full_path)
  51. def __call__(self, instance, filename):
  52. ext = filename.split('.')[-1]
  53. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  54. if instance.pk:
  55. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  56. else:
  57. filename = '{}.{}'.format(t, ext)
  58. return os.path.join(self.path, filename)
  59. @deconstructible
  60. class CertPath(object):
  61. def __init__(self, sub_path):
  62. self.path = sub_path
  63. self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
  64. if not os.path.exists(self.full_path):
  65. os.makedirs(self.full_path)
  66. def __call__(self, instance, filename):
  67. return os.path.join(self.path, filename)