file_operation.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. from PIL import Image
  8. def resizePicture(file, width):
  9. '''如果图片宽度或高度超过width,将图片宽度或高度修改为width'''
  10. try:
  11. img = Image.open(file)
  12. w, h = img.size
  13. if w > width or h > width:
  14. if w > h:
  15. size = (width, int(h * width / w))
  16. elif w < h:
  17. size = (int(w * width / h), width)
  18. else:
  19. size = (width, width)
  20. img = img.resize(size)
  21. img.save(file)
  22. except Exception as e:
  23. pass
  24. def UploadFile(file, upload_path):
  25. upload_path = PathAndRename(upload_path)
  26. filename = "%s%s.%s" % (
  27. upload_path.path,
  28. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  29. file.name.split('.')[-1]
  30. )
  31. filename = filename.lower()
  32. full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
  33. with open(full_filename, 'wb+') as destination:
  34. for chunk in file.chunks():
  35. destination.write(chunk)
  36. return filename
  37. def DownloadFace(url, save_path, ext):
  38. upload_path = PathAndRename(save_path)
  39. filename = "%s%s.%s" % (
  40. upload_path.path,
  41. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  42. ext
  43. )
  44. filename = filename.lower()
  45. full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
  46. response = requests.get(url)
  47. img = response.content
  48. with open(full_filename, 'wb+') as destination:
  49. destination.write(img)
  50. return filename
  51. def DeleteFile(filename):
  52. img_path = '%s/%s' % (settings.MEDIA_ROOT, filename)
  53. try:
  54. if os.path.exists(img_path):
  55. os.remove(img_path)
  56. except:
  57. pass
  58. @deconstructible
  59. class PathAndRename(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. ext = filename.split('.')[-1]
  67. t = timezone.now().strftime('%Y%m%d%H%M%S%f')
  68. if instance.pk:
  69. filename = '{}-{}.{}'.format(instance.pk, t, ext)
  70. else:
  71. filename = '{}.{}'.format(t, ext)
  72. return os.path.join(self.path, filename)