You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

67 rivejä
2.1 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 Meta:
  37. proxy = True
  38. class Pin(models.Model):
  39. submitter = models.ForeignKey(User)
  40. url = models.URLField(null=True)
  41. origin = models.URLField(null=True)
  42. referer = models.URLField(null=True)
  43. description = models.TextField(blank=True, null=True)
  44. image = models.ForeignKey(Image, related_name='pin')
  45. published = models.DateTimeField(auto_now_add=True)
  46. tags = TaggableManager()
  47. def __unicode__(self):
  48. return '%s - %s' % (self.submitter, self.published)
  49. @receiver(models.signals.post_delete, sender=Pin)
  50. def delete_pin_images(sender, instance, **kwargs):
  51. instance.image.delete()