Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

96 wiersze
2.8 KiB

  1. import requests
  2. from io import BytesIO
  3. from django.conf import settings
  4. from django.core.files.uploadedfile import InMemoryUploadedFile
  5. from django.db import models, transaction
  6. from django.dispatch import receiver
  7. from django_images.models import Image as BaseImage, Thumbnail
  8. from taggit.managers import TaggableManager
  9. from users.models import User
  10. class ImageManager(models.Manager):
  11. _default_ua = {
  12. 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) '
  13. 'AppleWebKit/537.36 (KHTML, like Gecko) '
  14. 'Chrome/48.0.2564.82 Safari/537.36',
  15. }
  16. # FIXME: Move this into an asynchronous task
  17. def create_for_url(self, url, referer=None):
  18. file_name = url.split("/")[-1].split('#')[0].split('?')[0]
  19. buf = BytesIO()
  20. headers = dict(self._default_ua)
  21. if referer is not None:
  22. headers["Referer"] = referer
  23. response = requests.get(url, headers=headers)
  24. buf.write(response.content)
  25. obj = InMemoryUploadedFile(buf, 'image', file_name,
  26. None, buf.tell(), None)
  27. # create the image and its thumbnails in one transaction, removing
  28. # a chance of getting Database into a inconsistent state when we
  29. # try to create thumbnails one by one later
  30. image = self.create(image=obj)
  31. for size in settings.IMAGE_SIZES.keys():
  32. Thumbnail.objects.get_or_create_at_size(image.pk, size)
  33. return image
  34. class Image(BaseImage):
  35. objects = ImageManager()
  36. class Sizes:
  37. standard = "standard"
  38. thumbnail = "thumbnail"
  39. square = "square"
  40. class Meta:
  41. proxy = True
  42. @property
  43. def standard(self):
  44. return Thumbnail.objects.get(
  45. original=self, size=self.Sizes.standard
  46. )
  47. @property
  48. def thumbnail(self):
  49. return Thumbnail.objects.get(
  50. original=self, size=self.Sizes.thumbnail
  51. )
  52. @property
  53. def square(self):
  54. return Thumbnail.objects.get(
  55. original=self, size=self.Sizes.square
  56. )
  57. class Pin(models.Model):
  58. submitter = models.ForeignKey(User)
  59. url = models.URLField(null=True, blank=True)
  60. origin = models.URLField(null=True, blank=True)
  61. referer = models.URLField(null=True, blank=True)
  62. description = models.TextField(blank=True, null=True)
  63. image = models.ForeignKey(Image, related_name='pin')
  64. published = models.DateTimeField(auto_now_add=True)
  65. tags = TaggableManager()
  66. def tag_list(self):
  67. return self.tags.all()
  68. def __unicode__(self):
  69. return '%s - %s' % (self.submitter, self.published)
  70. @receiver(models.signals.post_delete, sender=Pin)
  71. def delete_pin_images(sender, instance, **kwargs):
  72. try:
  73. instance.image.delete()
  74. except Image.DoesNotExist:
  75. pass