예제 #1
0
파일: views.py 프로젝트: 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/')
예제 #2
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)
예제 #3
0
파일: views.py 프로젝트: olegJF/eneyfoto
    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)
예제 #4
0
    def handle(self, *args, **options):
        collection = None
        print options["collection_id"]
        if options["collection_id"]:
          collection = Collection.objects.get(pk=options["collection_id"])

        photos = os.listdir(options['directory'])
        for photo_name in photos:
          print "photo name "+ photo_name
          photo_path = os.path.join(options['directory'], photo_name)
          if os.path.isfile(photo_path):
            print photo_path
            sub_id = os.path.splitext(os.path.basename(photo_path))[0]
            print sub_id
            if not Photo.objects.filter(subject_id=sub_id).exists():
      
              new_photo = Photo()
              if collection:
                new_photo.collection = collection
              filename = os.path.basename(photo_name)
              fobject  = open(photo_path)
              dfile = File(fobject)
              new_photo.image.save(filename, dfile)
              fobject.close()
              print str(new_photo)
            else:
              print "image already exists with subject_id of " + sub_id
예제 #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)
예제 #6
0
    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()
예제 #7
0
파일: views.py 프로젝트: philn/Gallery
def index(request):
    random = Photo.get_random(8)
    tags = Tag.get_cloud()
    t = settings.GALLERY_SETTINGS["recent_photos_time"]
    recent = Photo.get_random(8, since=(time.time() - t))
    recent_tags = Tag.get_recent_tags_cloud()
    params = {"random": random, "tags": tags, "recent": recent, "recent_tags": recent_tags}
    if hasattr(request, "openid"):
        params["openid"] = request.openid
    params.update(DEFAULT_PARAMS)
    return render_to_response("gallery/index.html", params, context_instance=RequestContext(request))
예제 #8
0
파일: views.py 프로젝트: MFreeze/photos
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()
예제 #9
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)
예제 #10
0
 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()
예제 #11
0
파일: views.py 프로젝트: philn/Gallery
def date(request, year, month, day, page=None):
    year = int(year)
    month = int(month)
    day = int(day)
    photo_set = Photo.for_date(year, month, day)
    video_set = Video.for_date(year, month, day)
    media_set = list(photo_set) + list(video_set)

    total = len(media_set)
    page, start, end, nb_pages = get_page(page, total)

    medias = media_set[start:end]
    total_pages = range(nb_pages)
    slug = "%s/date/%s/%s/%s/" % (G_URL, year, month, day)

    human_date = datetime.date(year, month, day).strftime("%A %d %B")

    params = {
        "year": year,
        "month": month,
        "day": day,
        "page": page,
        "slug": slug,
        "human_date": human_date,
        "nb_pages": nb_pages,
        "total_pages": total_pages,
        "medias": medias,
    }
    params.update(DEFAULT_PARAMS)
    return render_to_response("gallery/date.html", params, context_instance=RequestContext(request))
예제 #12
0
def photo_edit(request, *args, **kwargs):
    owner_id = kwargs.get('owner_id', None)
    gallery_id = kwargs.get('gallery_id', None)
    gallery = get_object_or_404(Gallery, pk=gallery_id)
    photo_id = kwargs.get('photo_id', None)

    if photo_id:
        edit = True
        photo = get_object_or_404(Photo, pk=photo_id)

    else:
        edit = False
        photo = Photo(gallery=gallery)

    if request.POST:
        form = PhotoForm(request.POST,
                         request.FILES,
                         instance=photo,
                         edit=edit)
        if form.is_valid():
            form.save()

            redirect_url = reverse('gallery', args=(owner_id, gallery_id))
            return HttpResponseRedirect(redirect_url)
    else:
        form = PhotoForm(instance=photo, edit=edit)

    context = {'form': form, 'edit': edit, 'photo': photo}
    return render(request, 'gallery/photo_edit.html', context)
예제 #13
0
파일: views.py 프로젝트: philn/Gallery
def recent(request, tag_name=None, page=None):
    tag = Tag.with_name(tag_name)
    if not tag:
        photo_set = Photo.recent()
        video_set = Video.recent()
    else:
        photo_set = tag.get_recent_photos()
        video_set = tag.get_recent_videos()

    media_set = list(photo_set) + list(video_set)
    total = len(media_set)
    page, start, end, nb_pages = get_page(page, total)

    medias = media_set[start:end]
    total_pages = range(nb_pages)

    slug = "/%s/recent/" % G_URL
    if tag_name:
        slug += "%s/" % tag_name

    params = {
        "tag": tag,
        "page": page,
        "slug": slug,
        "tag_name": tag_name,
        "nb_pages": nb_pages,
        "total_pages": total_pages,
        "medias": medias,
    }
    params.update(DEFAULT_PARAMS)
    return render_to_response("gallery/tag.html", params, context_instance=RequestContext(request))
예제 #14
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 '')))
예제 #15
0
파일: zip.py 프로젝트: 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
예제 #16
0
def browse(request):
    photos = Photo.show_all_photos()
    locations = Location.objects.all()
    return render(request,
                  "gallery/browse.html",
                  context={
                      "photos": photos,
                      "locations": locations
                  })
예제 #17
0
    def post(self, request, *args, **kwargs):
        from lists.models import MediaList

        if request.is_ajax():
            list, photos = MediaList.objects.get(uuid=self.kwargs["uuid"]), []
            for p in request.FILES.getlist('file'):
                photo = Photo.create_manager_photo(creator=request.user, image=p, list=list)
                photos += [photo]
            return render_for_platform(request, 'managers/manage_create/photo/new_manager_photos.html',{'object_list': photos})
        else:
            raise Http404
예제 #18
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)
예제 #19
0
    def import_photos(self, directory):
        pk_of_flickr_id = {}
        with exiftool.ExifTool(settings.EXIFTOOL, print_conversion=True) as et:
            exif_reader = ExifReader(et)
            log.debug(f"Importing photos from directory {directory}")

            for filename in glob.glob(f'{directory}/photo_*.json'):
                log.debug(f'Importing file {filename}')
                with open(filename, 'rt') as jf:
                    data = json.load(jf)
                    fid = data['id']
                    public = data['privacy'] == 'public'

                    photo_filenames = glob.glob(f'{directory}/*_{fid}_o.jpg')
                    if len(photo_filenames) != 1:
                        raise CommandError(
                            f"Image file for photo with Flickr ID {fid} not found"
                        )
                    old_filename = photo_filenames[0]
                    new_basename = os.path.basename(old_filename)
                    # Remove Flickr secret
                    new_basename = re.sub(r'(.*)_(\d+)_o\.(.+)', r'\1.\3',
                                          new_basename)

                    date_imported = datetime.strptime(data['date_imported'],
                                                      FLICKR_DATE_FORMAT)
                    date_imported = make_aware(date_imported)

                    # Create model instance
                    with open(old_filename, 'rb') as pf:
                        photo = Photo.create_with_exif(
                            exif_reader,
                            old_filename,
                            name=data['name'],
                            description=data['description'],
                            upload_date=date_imported,
                            public=public,
                            original=File(pf, name=new_basename),
                        )
                        # if existing_original:
                        #     # remove "original=... above
                        #     photo.original.name = existing_original
                        # else:
                        #     photo.original = File(pf, name=new_basename)

                        photo.save()
                        log.debug(f"Upload date: {photo.upload_date}")
                        log.debug(
                            f"Created photo model instance {vars(photo)}")
                        pk_of_flickr_id[fid] = photo.id
                        pass
            return pk_of_flickr_id
예제 #20
0
 def post(self, request, *args, **kwargs):
     if request.is_ajax():
         list, photos = request.user.get_photo_list(), []
         for p in request.FILES.getlist('file'):
             photo = Photo.create_photo(creator=request.user,
                                        image=p,
                                        list=list)
             photos += [photo]
         return render_for_platform(request,
                                    'user_gallery/new_list_photos.html',
                                    {'object_list': photos})
     else:
         raise Http404
예제 #21
0
    def test_photo_prev(self):
        user = User.query.get(1)
        photo2 = Photo(filename='test.jpg',
                       filename_s='test_s.jpg',
                       filename_m='test_m.jpg',
                       description='Photo 2',
                       author=user)
        photo3 = Photo(filename='test.jpg',
                       filename_s='test_s.jpg',
                       filename_m='test_m.jpg',
                       description='Photo 3',
                       author=user)
        photo4 = Photo(filename='test.jpg',
                       filename_s='test_s.jpg',
                       filename_m='test_m.jpg',
                       description='Photo 4',
                       author=user)
        db.session.add_all([photo2, photo3, photo4])
        db.session.commit()

        response = self.client.get(url_for('main.photo_previous', photo_id=1),
                                   follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Photo 2', data)

        response = self.client.get(url_for('main.photo_previous', photo_id=3),
                                   follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Photo 3', data)

        response = self.client.get(url_for('main.photo_previous', photo_id=4),
                                   follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Photo 4', data)

        response = self.client.get(url_for('main.photo_previous', photo_id=5),
                                   follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('This is already the first one.', data)
예제 #22
0
	def post(self, request, *args, **kwargs):
		from common.templates import render_for_platform

		list = PhotoList.objects.get(pk=self.kwargs["pk"])
		if request.is_ajax() and list.is_user_can_create_el(request.user.pk):
			photos = []
			uploaded_file = request.FILES['file']
			for p in request.FILES.getlist('file'):
				photo = Photo.create_photo(creator=request.user, image=p, list=list, type="PHLIS", community=list.community)
				photos += [photo,]
			return render_for_platform(request, 'gallery/new_photos.html',{'object_list': photos, 'list': list, 'community': list.community})
		else:
			raise Http404
예제 #23
0
 def get_context_data(self, **kwargs):
     """
     this method retrieves the comments related to the current photo
     :param kwargs:
     :return: data updated with comments
     """
     data = super().get_context_data(**kwargs)
     comments = Interaction.objects.filter(photo=self.get_object()).order_by('-created_at')
     comments = Photo.get_comments(self.get_object())
     data['interactions'] = comments
     if self.request.user.is_authenticated:
         data['comment_form'] = InteractionForm(instance=self.request.user)
     return data
예제 #24
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()
예제 #25
0
def search(request):
    
    if request.method == "GET":
        search_term = request.GET.get("search")
        searched_photos = Photo.search_photo_by_category(search_term)
        results = len(searched_photos)
        message = "{}".format(search_term)
        
        return render(request, "gallery/search.html", context={"message":message,
                                                               "photos":searched_photos,
                                                               "results":results})
    else:
        message = "You have not searched for any photo"
        return render(request, "gallery/search.html", context={"message":message})
예제 #26
0
파일: views.py 프로젝트: olegJF/eneyfoto
 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)
예제 #27
0
def commitedit(album, req):
	if not req.params.get("commit"):
		return HTTPFound(location = req.resource_url(album))

	s = DBSession()

	if req.params.get("new_album"):
		a = Album(parent_id = album.id)
		s.add(a)
		s.commit()
	else:
		a = album

	a.display_name = req.params.get("title")
	a.descr = req.params.get("description")
	a.hidden = bool(req.params.get("hide_album", 0))
	a.sort_by = int(req.params.get("sort_by", 1))

	new_thumb = req.params.get('album_thumbnail')
	print new_thumb, repr(new_thumb)
	if type(new_thumb) is types.InstanceType:
		old_preview = a.preview

		# add preview
		name = new_thumb.filename.lstrip(os.sep)
		preview = Photo(name, a.id, new_thumb.file.read())
		new_thumb.file.close()
		preview.hidden = True
		s.add(preview)
		s.commit()

		a.preview_id = preview.id
		if old_preview:
			s.delete(old_preview)

	s.commit()
	return HTTPFound(location = req.resource_url(a))
예제 #28
0
def upload():
    if request.method == 'POST' and 'file' in request.files:
        f = request.files.get('file')
        filename = rename_image(f.filename)
        f.save(os.path.join(current_app.config['ALBUMY_UPLOAD_PATH'],
                            filename))
        filename_s = resize_image(
            f, filename, current_app.config['ALBUMY_PHOTO_SIZE']['small'])
        filename_m = resize_image(
            f, filename, current_app.config['ALBUMY_PHOTO_SIZE']['medium'])
        photo = Photo(filename=filename,
                      filename_s=filename_s,
                      filename_m=filename_m,
                      author=current_user._get_current_object())
        db.session.add(photo)
        db.session.commit()
    return render_template('main/upload.html')
예제 #29
0
 def post(self, request, *args, **kwargs):
     community = Community.objects.get(pk=self.kwargs["pk"])
     if request.is_ajax() and request.user.is_administrator_of_community(
             community.pk):
         photo_input = request.FILES.get('file')
         _list = PhotoList.objects.get(community=community,
                                       type=PhotoList.AVATAR)
         photo = Photo.create_photo(creator=request.user,
                                    image=photo_input,
                                    list=_list,
                                    type="PHAVA",
                                    community=community)
         community.create_s_avatar(photo_input)
         community.create_b_avatar(photo_input)
         return HttpResponse()
     else:
         return HttpResponseBadRequest()
예제 #30
0
 def post(self, request, *args, **kwargs):
     user = User.objects.get(pk=self.kwargs["pk"])
     if request.is_ajax() and user == request.user:
         photo_input = request.FILES.get('file')
         _list = PhotoList.objects.get(creator=user,
                                       type=PhotoList.AVATAR,
                                       community__isnull=True)
         photo = Photo.create_photo(creator=user,
                                    image=photo_input,
                                    list=_list,
                                    type="PHAVA",
                                    community=None)
         request.user.create_s_avatar(photo_input)
         request.user.create_b_avatar(photo_input)
         return HttpResponse()
     else:
         return HttpResponseBadRequest()
예제 #31
0
 def post(self, request, *args, **kwargs):
     photos = []
     if request.is_ajax():
         list = PhotoList.objects.get(creator=request.user,
                                      type="WAL",
                                      community=None)
         for p in request.FILES.getlist('file'):
             photo = Photo.create_photo(creator=request.user,
                                        image=p,
                                        list=list,
                                        type="PHWAL",
                                        community=None)
             photos += [
                 photo,
             ]
         return render_for_platform(request, 'gallery/new_photos.html', {
             'object_list': photos,
             'list': list
         })
     else:
         raise Http404
예제 #32
0
    def test_collect(self):
        photo = Photo(filename='test.jpg',
                      filename_s='test_s.jpg',
                      filename_m='test_m.jpg',
                      description='Photo 3',
                      author=User.query.get(2))
        db.session.add(photo)
        db.session.commit()
        self.assertEqual(Photo.query.get(3).collectors, [])

        self.login()
        response = self.client.post(url_for('main.collect', photo_id=3),
                                    follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Photo collected.', data)

        self.assertEqual(
            Photo.query.get(3).collectors[0].collector.name, 'Normal User')

        response = self.client.post(url_for('main.collect', photo_id=3),
                                    follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Already collected.', data)
예제 #33
0
 def test_delete_method(self):
     Photo.delete_photo(self.photo.id)
     photos = Photo.objects.all()
     self.assertTrue(len(photos) == 0)
예제 #34
0
def photo(request):
    photos = Photo.show_all_photos()
    return render(request,
                  "all-galleries/photo.html",
                  context={"photos": photos})
예제 #35
0
파일: base.py 프로젝트: Xiaozekun/gallery
    def setUp(self):
        app = create_app('testing')
        self.context = app.test_request_context()
        self.context.push()
        self.client = app.test_client()
        self.runner = app.test_cli_runner()

        db.create_all()
        Role.init_role()

        admin_user = User(email='*****@*****.**',
                          name='Admin',
                          username='******',
                          confirmed=True)
        admin_user.set_password('123')
        normal_user = User(email='*****@*****.**',
                           name='Normal User',
                           username='******',
                           confirmed=True)
        normal_user.set_password('123')
        unconfirmed_user = User(email='*****@*****.**',
                                name='Unconfirmed',
                                username='******',
                                confirmed=False)
        unconfirmed_user.set_password('123')
        locked_user = User(email='*****@*****.**',
                           name='Locked User',
                           username='******',
                           confirmed=True,
                           locked=True)
        locked_user.set_password('123')
        locked_user.lock()

        blocked_user = User(email='*****@*****.**',
                            name='Blocked User',
                            username='******',
                            confirmed=True,
                            active=False)
        blocked_user.set_password('123')

        photo = Photo(filename='test.jpg',
                      filename_s='test_s.jpg',
                      filename_m='test_m.jpg',
                      description='Photo 1',
                      author=admin_user)
        photo2 = Photo(filename='test2.jpg',
                       filename_s='test_s2.jpg',
                       filename_m='test_m2.jpg',
                       description='Photo 2',
                       author=normal_user)

        comment = Comment(body='test comment body',
                          photo=photo,
                          author=normal_user)
        tag = Tag(name='test tag')
        photo.tags.append(tag)
        db.session.add_all([
            admin_user, normal_user, unconfirmed_user, locked_user,
            blocked_user
        ])
        db.session.commit()
예제 #36
0
def restore_album(d, s):
	adict = yaml.load(open(os.path.join(d, "info.yaml")))

	a = Album()

	a.id = adict["id"]
	a.display_name = adict["display_name"]
	a.created = adict["created"]
	a.preview_id = adict["preview_id"]
	a.descr = adict["descr"]
	a.hidden = adict["hidden"]
	a.sort_by = adict["sort_by"]
	s.add(a)
	s.commit()

	for pdict in adict["photos"]:
		pfile = pdict["name"]
		if pfile in ["previews", "info.yaml"]:
			continue
		ppath = os.path.join(d, pfile)
		if os.path.isdir(ppath):
			continue

		p = Photo()
		p.id = pdict["id"]
		p.album_id = a.id
		p.name = pdict["name"]
		p.display_name = pdict["display_name"]
		p.created = pdict["created"]
		p.width = pdict["width"]
		p.height = pdict["height"]
		p.hidden = pdict["hidden"]

		photo_name = os.path.basename(p.get_path())
		preview_name = os.path.basename(p.get_preview_path())

		shutil.copy(os.path.join(d, photo_name), p.get_path())
		shutil.copy(os.path.join(d, "previews", preview_name),
					p.get_preview_path())
		s.add(p)

	for afile in os.listdir(d):
		if afile == "previews":
			continue
		apath = os.path.join(d, afile)
		if not os.path.isdir(apath):
			continue

		restore_album(apath, s)
예제 #37
0
 def invalid():
     photo = Photo(user=self.admin,
                   image=None,
                   public=True)
     photo.save()
예제 #38
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)
예제 #39
0
 def test_get_photo_by_id(self):
     photo = Photo.get_photo_by_id(self.photo.id)
     self.assertEqual(photo, self.photo)
예제 #40
0
 def test_search_photo_by_category(self):
     photos = Photo.search_photo_by_category("Test")
     self.assertFalse(len(photos) > 0)
예제 #41
0
def index(request):
    photos = Photo.show_all_photos()
    return render(request, "gallery/index.html", context={"photos":photos})
예제 #42
0
 def test_filter_by_location(self):
     photos = Photo.filter_by_location(self.photo.id)
     self.assertTrue(len(photos) > 0)
        gallery, gallery_created = Gallery.objects.get_or_create(gallery_hash=gallery_hash)

        for f in files:
            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
예제 #44
0
파일: forms.py 프로젝트: degerli/ugallery
    def save_photos(self, gallery, group_cdn_url):
        group = FileGroup(group_cdn_url)

        for i, f in enumerate(group):
            Photo(gallery=gallery, title='Photo #{}'.format(i+1),
                  image=f).save()