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)
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)
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
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)
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_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)
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()
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')
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 '')))
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)
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()
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()