def setUp(self): super(ImageResizeTest, self).setUp() self.pp = Photo(title='portrait', title_slug='portrait') self.pp.image.save(os.path.basename(PORTRAIT_IMAGE_PATH), ContentFile(open(PORTRAIT_IMAGE_PATH, 'rb').read())) self.pp.save() self.ps = Photo( title='square', title_slug='square', ) self.ps.image.save(os.path.basename(SQUARE_IMAGE_PATH), ContentFile(open(SQUARE_IMAGE_PATH, 'rb').read())) self.ps.save()
def upload_photo(photo_path: str, gallery_name: str=None): """ Using Photo class from Photologue models upload photo to db """ photo_date = get_photo_date(photo_path) upload_date = datetime.now(pytz.timezone("US/Central")) photo_file_name = photo_path.split("/")[-1] photo_title = photo_file_name.replace(".jpg", "") # new_photo_path = ( # f"public/photogallery/media/photologue/photos/{photo_file_name}" # ) # photologue_path = f"photologue/photos/{photo_file_name}" # Move photo to photologue directory # shutil.copy(photo_path, new_photo_path) # os.rename(photo_path, new_photo_path) photo_model = Photo( image=photo_path, date_taken=photo_date, title=photo_title, slug=slugify(photo_title), caption='', date_added=upload_date, is_public=True ) LOG.info(f"Saving photo {photo_title} to {photo_path}") photo_model.save() if gallery_name: LOG.info(f"Saving photo {photo_title} to Gallery: {gallery_name}") add_photo_to_gallery(photo_obj=photo_model, gallery_name=gallery_name)
def setUp(self): user = GamerUser.objects.create_user('urtzai', '*****@*****.**', 'urtzaipass') user.is_superuser = True user.save() photo = Photo(title='GETB atala irudia', slug='gtb-atala-irudia', is_public=True) photo.image.save('test_photologue_landscape.jpg', ContentFile(open(LANDSCAPE_IMAGE_PATH, 'rb').read())) photo.save() Atala.objects.create(izenburua='GETB atala', slug='getb-atala', desk='Lehen atala duzue honako hau.', argazkia=photo, publikoa_da=True) plataforma = Plataforma.objects.create(izena='Play Station 4', slug='play-station-4') jokoa = Jokoa.objects.create(izena='Call of Duty', bertsioa='4', slug='call-of-duty-4', logoa=photo, publikoa_da=True) zailtasuna = Zailtasuna.objects.create(izena='Zaila', slug='zaila') kategoria = Kategoria.objects.create(izena='FPS', slug='fps', desk="First Person Shooter") gameplaya = GamePlaya(izenburua='Barrebusa 1', slug='barrebusa-1', desk="Espero dut gustuko izatea.", argazkia=photo, bideoa='c21XAuI3aMo', jokoa=jokoa, plataforma=plataforma, zailtasuna=zailtasuna, erabiltzailea=user, publikoa_da=True, status='1') gameplaya.save() gameplaya.kategoria.add(kategoria) gameplaya.save() gaia = Gaia.objects.create(izena='Berriak', slug='berriak') berria = Berria(izenburua='Switch argitaratu da', slug='switch-argitaratu-da', desk="Nintendoren kontsola berria argitaratu da.", erabiltzailea=user, argazkia=photo, jokoa=jokoa, publikoa_da=True, status='1') berria.save() berria.gaia.add(gaia) berria.save() txapelketa = Txapelketa.objects.create(izena='LoL txapelketa', slug="lol-txapelketa", desk="LoLeko beste txapelketa bat.", jokoa=jokoa) txapelketa.adminak.add(user)
def handle_photo_file(f, title): """ """ photo = Photo() photo.title = u'%s %s' % (time_slug_string(), title) photo.title_slug = time_slug_string() photo.image = f photo.save() return photo
def markdown_uploader(request): """ Markdown image upload to Image db object (using default storage) and represent as json for markdown editor. """ if request.method == 'POST' and request.is_ajax(): if 'markdown-image-upload' in request.FILES: image = request.FILES['markdown-image-upload'] image_types = [ 'image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif' ] if image.content_type not in image_types: data = json.dumps( { 'status': 405, 'error': _('Bad image format.') }, cls=LazyEncoder) return HttpResponse(data, content_type='application/json', status=405) if image.size > settings.MAX_IMAGE_UPLOAD_SIZE: to_MB = settings.MAX_IMAGE_UPLOAD_SIZE / (1024 * 1024) data = json.dumps( { 'status': 405, 'error': _('Maximum image file is %(size) MB.') % { 'size': to_MB } }, cls=LazyEncoder) return HttpResponse(data, content_type='application/json', status=405) slug = "{0}-{1}".format(uuid.uuid4().hex[:10], slugify(image.name)) photo_db = Photo( image=image, title=slug, slug=slug, ) photo_db.save() image_url = reverse('utils:photo_SIZE_by_slug', args=[photo_db.slug, 'medium']) data = json.dumps({ 'status': 200, 'link': image_url, 'name': photo_db.title }) return HttpResponse(data, content_type='application/json') return HttpResponse(_('Invalid request!')) return HttpResponse(_('Invalid request!'))
def handle_uploaded_screenshot(content): """ :param content: Image info :type content: dict :return: Result Dict :rtype: dict """ result_dict = {} try: image_dir = os.path.join(settings.MEDIA_ROOT, 'photologue', 'photos') if not os.path.isdir(image_dir): mkdir_p(image_dir) file_name = os.path.basename(content['path']) with transaction.atomic(): content_id = content['id'] content_slug = content['slug'] gallery = Gallery.objects.filter(slug=content_slug).last() current_site = Site.objects.get(id=settings.SITE_ID) p_version = Version.objects.get(id=content_id) c_name = re.sub('[^A-Za-z0-9]', '', p_version.c_name) # filter if gallery: pass else: # create a new gallery gallery = Gallery.objects.create(title=c_name, slug=content_slug, description=p_version.c_depiction if p_version.c_depiction else 'None', is_public=1) gallery.sites.add(current_site) # save photo = Photo(title=c_name + '_' + str(uuid.uuid1()), slug=c_name.lower() + '_' + str(uuid.uuid1()), caption='', is_public=1) data = open(content['path'], 'rb') content_file = ContentFile(data.read()) photo.image.save(file_name, content_file) photo.save() photo.sites.add(current_site) gallery.photos.add(photo) data.close() if p_version.gallery is None: p_version.gallery = gallery p_version.save() result_dict.update({ "success": True, "version": p_version.id }) except Exception as e: # error handler result_dict.update({ "success": False, "exception": str(e) }) return result_dict
def get_image_from_url(data): try: image = Photo.objects.get(slug=data['slug']) except Photo.DoesNotExist: url = data.pop('image', None) name, file = get_serialized_image(url) del data['sites'] image = Photo(**data) image.image.save(name, file, save=True) image.save() return image
def uploadimagejson(request): p = Photo() if request.user.is_authenticated(): if request.method == 'POST': pt = codegenerator() + codegenerator() p.image = request.FILES['file'] p.title = pt p.title_slug = slugify(pt) #+codegenerator() p.save() # template = loader.get_template('redactorimageupload.html') params = {'photo': p} # context = RequestContext(request, params) return render_to_response('redactorimageupload.html', params, context_instance=RequestContext(request))
def save(self): data = self.cleaned_data photo = Photo() photo.title = data.get('title') photo.slug = re.sub(' +', '_', photo.title) photo.caption = data.get('caption') if (data.get('image') is not None): img_file = data.get('image') photo.image.save('%s' % (img_file.name), img_file, save=True) photo.save() galleries = data.get('galleries') if galleries is not None: for gallery in galleries: gallery.photos.add(photo) gallery.save() return photo
def loadUrlImage(url='', title='', tags='', format='jpg', slug=''): """ """ if not url: url = 'http://irudiak.argazkiak.org/1d3023545b4051907e533648e66329f8_c.jpg' title = 'Kakalardoa' tags = 'test argazkiak' if not slug: slug = time_slug() if Photo.objects.filter(slug=slug): slug = time_slug_long() title = title[:99] if Photo.objects.filter(title=title): title = '%s %s' % (slug, title)[:90] image = _getUrlImage(url) if not image: return None photo = Photo() photo.title = title[:100] photo.tags = tags photo.slug = slug try: image_t = Image.open(ContentFile(image.read())) image_t = image_t.convert("RGB") f=StringIO() image_t.save(f,"JPEG") f.seek(0) photo.image.save('%s.%s' % (slug,format), ContentFile(f.read())) except Exception: print('Errorea irudi honekin RGB', photo.slug) return photo try: photo.save() except: print('Errorea irudi honekin', photo.slug) return photo
def test_quoted_url(self): """Test for issue #29 - filenames of photos are incorrectly quoted when building a URL.""" # Check that a 'normal' path works ok. self.assertEqual( self.pl.get_testPhotoSize_url(), self.pl.cache_url() + '/test_landscape_testPhotoSize.jpg') # Now create a Photo with a name that needs quoting. self.pl2 = Photo(title='test', title_slug='test') self.pl2.image.save(os.path.basename(QUOTING_IMAGE_PATH), ContentFile(open(QUOTING_IMAGE_PATH, 'rb').read())) self.pl2.save() self.assertEqual( self.pl2.get_testPhotoSize_url(), self.pl2.cache_url() + '/test_%26quoting_testPhotoSize.jpg')
def clean_new_image(self): """Let's take the uploaded image, create a new photo and bind to the image field in model""" rand_int = random.randint(1,99) if self.cleaned_data['image']: image = self.cleaned_data['image'] if self.cleaned_data['new_image']: image.image = self.cleaned_data['new_image'] image.save() self.cleaned_data['image'] = image else: new_photo = Photo(image=self.cleaned_data['new_image'], title= "%s %s %s" %(self.cleaned_data['title'], self.cleaned_data['seller'].user.username, rand_int), title_slug = "%s_%s" %(self.cleaned_data['slug_url'], rand_int)) new_photo.save() self.cleaned_data['image'] = new_photo return self.cleaned_data['image']
def save(self, request=None, zip_file=None): print(self.cleaned_data['gallery_type']) if not zip_file: zip_file = self.cleaned_data['zip_file'] encoded = zip_file._name.encode('utf-8').decode() zipname = encoded.split('.')[0] zip = zipfile.ZipFile(zip_file) count = 1 current_site = Site.objects.get(id=settings.SITE_ID) if self.cleaned_data['gallery']: logger.debug('Using pre-existing gallery.') gallery = self.cleaned_data['gallery'] else: logger.debug( force_text('Creating new gallery "{0}".').format( self.cleaned_data['title'])) gallery_type_cls = { 'WEDDING': Wedding, 'LOVESTORY': Lovestory, 'FAMILY': Family, 'PORTRAIT': Portrait, 'TRAVEL': Travel, } gallery = gallery_type_cls[ self.cleaned_data['gallery_type']].objects.create( title=self.cleaned_data['title'], slug=slugify(self.cleaned_data['title']), description=self.cleaned_data['description'], is_public=self.cleaned_data['is_public']) gallery.sites.add(current_site) for filename in sorted(zip.namelist()): logger.debug('Reading file "{0}".'.format(filename)) if filename.startswith('__') or filename.startswith('.'): logger.debug('Ignoring file "{0}".'.format(filename)) continue if os.path.dirname(filename): logger.warning('Ignoring file "{0}" as it is in a subfolder;\ all images should be in the top ' 'folder of the zip.'.format(filename)) if request: messages.warning(request, _('Ignoring file "{filename}"\ as it is in a subfolder;\ all images should \ be in the top folder of the zip.'). format(filename=filename), fail_silently=True) continue data = zip.read(filename) if not len(data): logger.debug('File "{0}" is empty.'.format(filename)) continue photo_title_root = self.cleaned_data['title'] if self.cleaned_data[ 'title'] else gallery.title # A photo might already exist with the same slug. So it's somewhat inefficient, # but we loop until we find a slug that's available. while True: photo_title = ' '.join([photo_title_root, str(count)]) slug = slugify(photo_title) if Photo.objects.filter(slug=slug).exists(): count += 1 continue break photo = Photo(title=photo_title, slug=slug, caption=self.cleaned_data['caption'], is_public=self.cleaned_data['is_public']) # Basic check that we have a valid image. try: file = BytesIO(data) opened = Image.open(file) opened.verify() except Exception: # Pillow (or PIL) doesn't recognize it as an image. # If a "bad" file is found we just skip it. # But we do flag this both in the logs and to the user. logger.error( 'Could not process file "{0}" in the .zip archive.'.format( filename)) if request: messages.warning( request, _('Could not process file "{0}" in the .zip archive.' ).format(filename), fail_silently=True) continue contentfile = ContentFile(data) photo.image.save("%s/%s" % (zipname, filename), contentfile) photo.save() photo.sites.add(current_site) gallery.photos.add(photo) count += 1 zip.close() if request: messages.success( request, _('The photos have been added to gallery "{0}".').format( gallery.title), fail_silently=True)
def insertIntoGallery(gallery_title, gallery_slug, screenshot, title, slug, gallery_description="", gallery_tags="", caption="", tags="", fab_dir='%s/.fabric-bolt' % (os.path.expanduser('~/'))): # Add custom fabric-bolt settings directory sys.path.insert(0, fab_dir) # Utilize django within fabfile # Load custom fabric-bolt settings file django.settings_module('settings') # Loads the django Models get_wsgi_application() # Once loaded we can reference them from photologue.models import Photo from photologue.models import Gallery file = open(screenshot, 'rb') data = file.read() # First Generate or Retrieve the Photo Model and save or update it try: photo = Photo.objects.get(slug=slug) photo.date_added = datetime.now() photo.date_taken = datetime.now() print("~~~ FOUND existing Screenshot ~~~") except Photo.DoesNotExist: photo = Photo( title=title, slug=slug, caption=caption, is_public=True, tags=tags, ) print("~~~ CREATED new Screenshot ~~~") try: photo.image.save(os.path.basename(screenshot), ContentFile(data)) except FieldError: # For some reason a field, 'photo,' is being passed to model as a field. pass print("~~~ SAVED Screenshot ~~~") # Now Create or Retrieve the named Gallery and add the photo to it. gallery = None try: gallery = Gallery.objects.get(title=gallery_title) print("~~~ FOUND existing Screenshot Gallery ~~~") except Gallery.DoesNotExist: gallery = Gallery( title=gallery_title, slug=gallery_slug, description=gallery_description, is_public=True, tags=gallery_tags, ) gallery.save() print("~~~ CREATED new Screenshot Gallery ~~~") if gallery: gallery.photos.add(photo) print("~~~ Added Screenshot to Gallery ~~~") print( "<a target=\"_parent\" href=\"/photologue/gallery/%s\">View Screenshot Gallery %s</a>" ) % (gallery_title, gallery_title) # Reset the syspath sys.path.remove(fab_dir)
def post(request, category="", success_url=None, form_class=NewsForm, template_name='news/news_post.html', extra_context=None): if category != "": c = get_object_or_404(Category.objects.all(), slug=category) else: c = None if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.deliverer = request.user instance.save() form.save_m2m() #kwargs = {} #kwargs['title'] = _("%s Posted A new News: %s") % (self.deliverer.username,self.title) #kwargs['content'] = _("%s Posted A new News,go and view it now <a href='%s'> %s </a> " ) % (self.deliverer.username,self.get_absolute_url(),self.title) #kwargs['slug'] = "news%d-%s" % (self.id,datetime.datetime.now().strftime("%Y%m%d%H%M%S")) #latest_news_created.send(sender=self.__class__,**kwargs) if form.files: gallery = NewsPhotoGallery.objects.create( title="%s-%d" % (instance.title, instance.id), title_slug="%s-%d" % (instance.slug, instance.id), description=instance.title, date_added=instance.pub_date, tags=instance.tags) instance.gallery = gallery instance.save() counter = 1 photofile_fieldlist = form.files.keys() #d() #for photofilefield in form.files: for photofilefield in sorted(photofile_fieldlist): photo_file = form.files[photofilefield] photo = Photo(title='-'.join([gallery.title, str(counter)]), title_slug='-'.join([ gallery.title_slug, str(gallery.id), 'p', str(counter) ]), caption=gallery.description, tags=gallery.tags) photo.image.save(photo_file.name, photo_file) gallery.photos.add(photo) counter = counter + 1 if photofilefield == u"file": if not gallery.cover: gallery.cover = photo gallery.save() return HttpResponseRedirect(instance.get_absolute_url()) else: #initial={'category':c.id, 'deliverer':request.user.id} initial = {'deliverer': request.user.id} form = form_class(initial=initial) if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response(template_name, { 'form': form, 'category': c, }, context_instance=context)
def _create_new_photo(name, slug): pl = Photo(title=name, title_slug=slug) pl.image.save(os.path.basename(LANDSCAPE_IMAGE_PATH), ContentFile(open(LANDSCAPE_IMAGE_PATH, 'rb').read())) pl.save() return pl
def process_zipfile(self): if os.path.isfile(self.zip_file.path): # TODO: implement try-except here zip = zipfile.ZipFile(self.zip_file.path) bad_file = zip.testzip() if bad_file: raise Exception('"%s" in the .zip archive is corrupt.' % bad_file) count = 1 if self.category: category = self.category else: raise Exception('must choose a category') for filename in sorted(zip.namelist()): if filename.startswith('__'): # do not process meta files continue data = zip.read(filename) if len(data): try: # the following is taken from django.newforms.fields.ImageField: # load() is the only method that can spot a truncated JPEG, # but it cannot be called sanely after verify() trial_image = Image.open(StringIO(data)) 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(StringIO(data)) trial_image.verify() except Exception: # if a "bad" file is found we just skip it. continue while 1: title = ' '.join([self.title, str(count)]) slug = slugify(title) try: p = Photo.objects.get(title_slug=slug) except Photo.DoesNotExist: photo = Photo(title = title, title_slug = slug, caption = self.caption, is_public = self.is_public, tags = self.tags) photo.image.save(filename, ContentFile(data)) gallery.photos.add(photo) count = count + 1 break count = count + 1 zip.close() return gallery for key in d.keys(): if key[0:4]=='name': #i=int(key[4:]) #print d[key],'=',d['url'+key[4:]] title = d[key] try: url = d['url'+key[4:]] except KeyError: continue link=Link( title = title, category = category, url = url, notes = title, pub_date = datetime.date.today(), ) link.save() return category
def import_movie(movie_id): movie_id = movie_id.strip( '\n' ) # Newline character was preventing the movie table from being searchable by ID. data = { 'title': '', 'canonical title': '', 'year': None, 'rating': None, 'plot': '', # IMDB provides list of plots from different contributors. 'plot outline': '', 'genres': '', #IMDB provides list of genres. 'mpaa': 'Mpaa not available.', 'runtimes': '', 'full-size cover url': '', 'imdbId': movie_id, 'director': '', 'cast': '', } movie = IMDb().get_movie(movie_id) title = unicodedata.normalize('NFKD', movie['title']).encode('ascii', 'ignore') for key in data: if movie.has_key(key): if key == 'director' or key == 'cast': plist = [person['name'] for person in movie[key]] movie[key] = ', '.join(plist[0:3]) elif type(movie[key]) == type([]) and key != 'genres': movie[key] = movie[key][0] if type(movie[key]) == type(''): movie[key] = unicodedata.normalize('NFKD', movie[key]).encode( 'ascii', 'ignore') data[key] = movie[key] elif key != 'imdbId': print 'Error! {} not available in {}'.format(key, title) cover = None try: imagedata = urllib2.urlopen(data['full-size cover url']).read() cover = Photo(title=data['title'], title_slug=slugify(data['title'])) cover.image.save(data['imdbId'] + '.jpg', ContentFile(imagedata)) print "saved an image: " + data['title'] except Exception as e: print "Oh noes, an error" print e pass m = Movie(title=data['title'], canonicalTitle=data['canonical title'], year=data['year'], rating=data['rating'], plot=data['plot'], plotOutline=data['plot outline'], mpaa=data['mpaa'], runtimes=data['runtimes'], cover=cover, imdbId=data['imdbId'], director=data['director'], cast=data['cast']) m.save() try: gs = [Genre.objects.get(name=g) for g in data['genres']] except Exception as e: gs = [] print "No genre found for " + g gs.append(Genre.objects.get(name='New')) gs.append(Genre.objects.get(name='All')) m.genres = gs m.save()