Esempio n. 1
0
File: views.py Progetto: lpcpp/www
def upload_photo(request):
    if request.user.is_authenticated():
        if request.method == "POST":
            logger.debug('FFFFFFFILES==%s', request.FILES)
            pf = PhotoForm(request.POST, request.FILES)
            logger.debug('pf====%s', pf)
            if pf.is_valid():
                name = pf.cleaned_data['name']
                photos = Photo.objects.filter(name=name)
                if photos:
                    error = 'this photo name has already exist, please use another one'
                    return render_to_response('gallery/upload_photo.html', {'pf': pf, 'error': error}, context_instance=RequestContext(request))
                album = pf.cleaned_data['album']
                fn = request.FILES['img'].name
                url = handle_upload_photo(request.FILES['img'], str(album), fn)
                thumbnail = make_thumbnail(url) 
                # thumbnail = make_thumbnail(request.FILES['img']) 
            
                #img字段不再用来存储上传的图像,而是存储生成的缩略图thumbnail
                photo = Photo(name=name, url=url, img=thumbnail, album=album)
                photo.save()
                return HttpResponseRedirect('/gallery/upload_photo_success/')
        else:
            pf = PhotoForm()
            albums = Album.objects.all()
        return render_to_response('gallery/upload_photo.html', {'pf': pf, 'request': request}, context_instance=RequestContext(request))

    return HttpResponseRedirect('/login/')
Esempio n. 2
0
    def recreate_photodb(self):
        self._recreate_thumbs()
        self._recreate_default_tags()
        self._delete_photos_from_db()
        self._fill_photo_list()

        for photo in self._photos:
            # Save path of photo and thumbnail without 'static' prefix
            full_path = photo[len('static/'):]
            thumbnail = path.join(path.dirname(photo), self._thumbs_dirname,
                                  path.basename(photo))[len('static/'):]
            name = path.basename(photo)
            create_date = timezone.now()

            # TODO: add exception (if tag not found)
            default_tag = Tag.objects.get(name=path.basename(path.dirname(photo)))

            photo_item = Photo()
            photo_item.name = name
            photo_item.full_path = full_path
            photo_item.thumbnail = thumbnail
            photo_item.create_date = create_date
            photo_item.is_album_orientation = self.is_album_orientation(photo)
            photo_item.save()
            photo_item.tags.add(default_tag)
Esempio n. 3
0
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file_field')
        if form.is_valid():
            album_id = request.POST['item']
            if request.POST['title']:
                title = request.POST['title']
            else:
                title = ''
            if request.POST['caption']:
                caption = request.POST['caption']
            else:
                caption = ''
            for f in files:
                one_image = Photo(item_id=album_id,
                                  image=f,
                                  title=title,
                                  caption=caption)
                one_image.save()
            if len(files) > 1:
                messages.success(request, 'Фотографии добавлены')
            else:
                messages.success(request, 'Фотография добавлена')

            return self.form_valid(form)
        else:
            return self.form_invalid(form)
Esempio n. 4
0
 def addPhoto(content, title = "", comment = "", isUrl=False):
     Logger.LogParameters(funcname = sys._getframe().f_code.co_name, func_vars = vars(), module = "PhotoManager")
     try:
         imageName = RandomID.gen()
         
         if not isUrl:
             fileObj = StringIO(content.read())
         else:
             #url = "http://www.didao8.com:8080/static/44/thumb/nvLcHMu1JS3mepZPkQBqriG4ANthz2s5.jpg"
             fileObj = StringIO(urllib2.urlopen(content).read())
             
         img = Image.open(fileObj)
         width, height = img.size
         fileName = "%s%s%s" % (imageName, ".", img.format)
         filePath = (PHOTO_DATA_ROOT + "%s") % fileName
         img.save(filePath)
         
         photo = Photo(title=title, comment=comment, datetime = time.time(),
                       imageName=fileName, width = width, height = height)
         photo.save()
         
         return Err.genOK(photo.id)
     except Exception, ex:
         print ex
         Logger.SaveLogDebug(ex, level=Logger.LEVEL_ERROR, module = "PhotoManager")
         return Err.genErr(Err.ERR_ADD_PHOTO_FAIL)
Esempio n. 5
0
 def test_sanity(self):
     """
     Creating a simple photo without exif.
     """
     photo = Photo(user=self.admin,
                   image=ImageFile(open(PATH_MANA, 'rb')),
                   public=True)
     photo.save()
     self.assertFalse(photo.exif_available)
Esempio n. 6
0
def handle_uploaded_file(f, upload_auth):
    with open(settings.MEDIA_ROOT + str(f), 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    arc = zipfile.ZipFile(settings.MEDIA_ROOT + "77_toutes_photos.zip", "a",
                          zipfile.ZIP_DEFLATED)
    before = os.listdir(settings.MEDIA_ROOT)
    try:
        shutil.unpack_archive(settings.MEDIA_ROOT + str(f),
                              extract_dir=settings.MEDIA_ROOT)
    except Exception as e:
        os.remove(settings.MEDIA_ROOT + str(f))
        raise Exception(e)
    after = os.listdir(settings.MEDIA_ROOT)
    diff = [fpath for fpath in after if fpath not in before]
    #print(diff)

    for i in diff:
        #print(i)
        path = settings.MEDIA_ROOT + i
        im_name = upload_auth.firstname + "_" + upload_auth.lastname + "_" + i
        mid_thumb = "m_" + im_name
        small_thumb = "s_" + im_name
        # Create Thumbnails
        tmp_pict = Image.open(path)
        ratio = max(tmp_pict.size[0] / 950, tmp_pict.size[1] / 712)
        tmp_pict.thumbnail(tuple([int(x / ratio) for x in tmp_pict.size]),
                           Image.ANTIALIAS)
        tmp_pict.save(mid_thumb, tmp_pict.format)
        tmp_pict.close()

        tmp_pict = Image.open(path)
        ratio = max(tmp_pict.size[0] / 130, tmp_pict.size[1] / 98)
        tmp_pict.thumbnail(tuple([int(x / ratio) for x in tmp_pict.size]),
                           Image.ANTIALIAS)
        tmp_pict.save(small_thumb, tmp_pict.format)
        tmp_pict.close()

        # Create an Photo instance
        photo = Photo(author=upload_auth)
        photo.med_thumb.save(mid_thumb, ImageFile(open(mid_thumb, 'rb')))
        photo.small_thumb.save(small_thumb, ImageFile(open(small_thumb, 'rb')))
        photo.save()

        os.rename(path, settings.MEDIA_ROOT + im_name)
        arc.write(settings.MEDIA_ROOT + im_name)
        os.remove(settings.MEDIA_ROOT + im_name)
        os.remove(mid_thumb)
        os.remove(small_thumb)
    os.remove(settings.MEDIA_ROOT + str(f))
    arc.close()
Esempio n. 7
0
    def handle(self, *args, **options):
        count = options['count']
        if count < 1 or count > 1000:
            raise CommandError('Count must be between 1 and 1000')

        numPhotos = Photo.objects.count()
        for i in range(count):
            newPhoto = Photo(
                title='Number {}'.format(i + numPhotos),
                price=200,
                url='https://picsum.photos/id/{0}/400/400?random={1}'.format(
                    i, i + numPhotos))
            newPhoto.save()

        self.stdout.write(
            self.style.SUCCESS('Successfully created {0} photo{1}'.format(
                count, 's' if count > 1 else '')))
Esempio n. 8
0
File: zip.py Progetto: sebjam/capa
def process_zipfile(file_path, gallery):
    bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
    if os.path.isfile(file_path):
        zip = zipfile.ZipFile(file_path)
        bad_file = zip.testzip()
        if bad_file:
            raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
        count = 1
        for filename in sorted(zip.namelist()):
            data = zip.read(filename)
            string_buffer = BytesIO(data)
            if len(data):
                try:
                    # load() is the only method that can spot a truncated JPEG,
                    # but it cannot be called sanely after verify()
                    trial_image = Image.open(string_buffer)
                    trial_image.load()
                    # verify() is the only method that can spot a corrupt PNG,
                    #  but it must be called immediately after the constructor
                    trial_image = Image.open(string_buffer)
                    trial_image.verify()
                except Exception:
                    # if a "bad" file is found we just skip it.
                    continue
                while 1:
                    title = '{}-{}'.format(filename, str(count))
                    key = Key(bucket)
                    key.key = title
                    key.set_contents_from_file(string_buffer)
                    url = key.generate_url(
                        expires_in=0,
                        query_auth=False,
                        force_http=True
                    )
                    photo = Photo(
                        parent=gallery,
                        title=title,
                        image=url
                    )
                    photo.save()
                    count = count + 1
                    break
                count = count + 1
        zip.close()
        return True
Esempio n. 9
0
class PhotoTestClass(TestCase):
    """
    Creating the initial instance of the Photo class
    """
    def setUp(self):
        self.place = Location(city="Nairobi", country="Kenya")
        self.place.save()

        self.category = Category(name="Test")
        self.category.save()

        self.photo = Photo(name='A random title',
                           description="A random description",
                           location=self.place)
        self.photo.save()

    def test_instance(self):
        self.assertTrue(isinstance(self.photo, Photo))

    def test_save_method(self):
        self.photo.save_photo()
        photos = Photo.objects.all()
        self.assertTrue(len(photos) > 0)

    def test_delete_method(self):
        Photo.delete_photo(self.photo.id)
        photos = Photo.objects.all()
        self.assertTrue(len(photos) == 0)

    def test_get_photo_by_id(self):
        photo = Photo.get_photo_by_id(self.photo.id)
        self.assertEqual(photo, self.photo)

    def test_search_photo_by_category(self):
        photos = Photo.search_photo_by_category("Test")
        self.assertFalse(len(photos) > 0)

    def test_filter_by_location(self):
        photos = Photo.filter_by_location(self.photo.id)
        self.assertTrue(len(photos) > 0)
Esempio n. 10
0
 def post(self, request, *args, **kwargs):
     form_class = self.get_form_class()
     form = self.get_form(form_class)
     files = request.FILES.getlist('file_field')
     if form.is_valid():
         album_id = request.POST['item']
         if request.POST['title']:
             title = request.POST['title']
         else: title =''
         if request.POST['caption']:
             caption = request.POST['caption']
         else: caption = ''
         for f in files:
             one_image = Photo(item_id=album_id, image=f,
                               title=title, caption=caption)
             one_image.save()
         if len(files) >1:
             messages.success(request, 'Фотографии добавлены') 
         else: messages.success(request, 'Фотография добавлена')
         
         return self.form_valid(form)
     else:
         return self.form_invalid(form)
Esempio n. 11
0
class GalleryTestCase(TestCase):
    urls = 'gallery.urls'
    # Fixtures tak łatwo nie przejdą, obrazy wszukiwane są w site_media,
    # które w apce trudno jest t
    # fixtures = ['images.yaml']

    def login_user(self):
        self.client.login(username='******', password='******')

    def setUp(self):
        # Typowy użytkownik, nick admin nic nie znaczy
        self.admin = User.objects.create_user(
            username='******', password='******', email='*****@*****.**')
        # Tworzenie zdjęć ręcznie zamiast używania fixtures - muszę zostać
        # zuploadowane do odpowiedniego katalogu
        self.photo_mana = Photo(user=self.admin,
                                image=ImageFile(open(PATH_MANA, 'rb')),
                                public=False)
        self.photo_mana.save()
        self.photo_grodek = Photo(user=self.admin,
                                  image=ImageFile(open(PATH_GRODEK, 'rb')),
                                  public=True)
        self.photo_grodek.save()
            src = os.path.join(path, f)

            fh = open(src)
            h = hashlib.sha1()
            h.update(fh.read())
            image_hash = h.hexdigest()
            fh.close()

            try:
                photo = Photo.objects.get(image_hash=image_hash)
            except Photo.DoesNotExist:
                photo = Photo(image_hash=image_hash)

            if not photo.image:  # new photo
                dst_relative = os.path.join(photo.image.field.upload_to, f)
                dst = os.path.join(photo.image.storage.location, dst_relative)
                shutil.copy2(src, dst)
                fn, fe = os.path.splitext(os.path.basename(dst))
                photo.image = dst_relative
                photo.gallery = gallery
                photo.published_at = datetime.now()
                photo.name = fn
                photo.save()

        if gallery_created:  # new gallery
            gallery.name = gallery_name
            gallery.cover = photo
            gallery.save()

    order += 1
Esempio n. 13
0
 def test_exif(self):
     photo = Photo(user=self.admin,
                   image=ImageFile(open(PATH_GRODEK, 'rb')),
                   public=True)
     photo.save()
     self.assertTrue(photo.exif_available)
Esempio n. 14
0
 def invalid():
     photo = Photo(user=self.admin,
                   image=None,
                   public=True)
     photo.save()