def photos_from_zip(path,approved=True,user=None): """turn a zip file into a photos""" now = datetime.datetime.now() _ = now.strftime(Photo._meta.get_field('file').upload_to) zip_name = path.split('/')[-1] root = os.path.join(settings.MEDIA_ROOT,_) if not os.path.exists(root): os.mkdir(root) directory = os.path.join(root,'%s_%s'%(now.day,now.time())) os.mkdir(directory) new_path = os.path.join(directory,zip_name) os.chdir(directory) os.rename(path,new_path) command = 'unzip %s'%new_path process = Popen(command, stdout=PIPE, shell=True) process.communicate() for folder,_,files in os.walk('.'): for f in files: os.rename(os.path.join(folder,f),os.path.join(directory,f)) folders = [f for f in os.listdir(directory) if os.path.isdir(f)] for f in folders: os.rmdir(f) files = [f for f in os.listdir(directory) if not os.path.isdir(f)] for f_path in files: print "creating photo!" photo = Photo( file = os.path.join(directory,f_path).split(settings.MEDIA_ROOT)[-1], source = "misc", approved = approved, user=user ) photo.save() #all done, delete the zip! os.remove(new_path)
def getTrailsAndPhotos(lon, lat, cnt, resort, trails, photos): """ gets all trails nearby given resort associates all created trails with resortid and adds photo for trail into the photos for the resort """ data = None try: if resort is None: data = fetch.fetchJSON( 'https://www.hikingproject.com/data/get-trails?lat=' + str(lat) + '&lon=' + str(lon) + '&maxDistance=10&maxResults=' + str(cnt) + '&sort=distance&key=200217902-4d9f4e11973eb6aa502e868e55361062' ) else: data = fetch.fetchJSON( 'https://www.hikingproject.com/data/get-trails?lat=' + str(resort.lat) + '&lon=' + str(resort.lon) + '&maxDistance=10&maxResults=' + str(cnt) + '&sort=distance&key=200217902-4d9f4e11973eb6aa502e868e55361062' ) except ValueError as e: return trails, photos for t in data['trails']: if t['id'] not in trails: trail = Trail(name=t['name'], id=t['id']) trail.difficulty = t['difficulty'] if 'difficulty' in t else None trail.summary = t['summary'] if 'summary' in t else None trail.stars = t['stars'] if 'stars' in t else None trail.starVotes = t['starVotes'] if 'starVotes' in t else None trail.lat = t['latitude'] if 'latitude' in t else None trail.lon = t['longitude'] if 'longitude' in t else None trail.length = t['length'] if 'length' in t else None trail.ascent = t['ascent'] if 'ascent' in t else None trail.descent = t['descent'] if 'descent' in t else None try: youtubedata = fetch.fetchJSON( 'https://www.googleapis.com/youtube/v3/search?q=' + trail.name + ' trail' + '&part=snippet&type=video&maxResults=25&key=AIzaSyDRwflQaI1Zq5bqKVQJ2YBDHb7l7oD1L2o' ) trail.youtubeid = youtubedata['items'][0]['id']['videoId'] except ValueError: trail.youtubeid = None except IndexError: trail.youtubeid = None trails[t['id']] = trail if 'imgMedium' in t and t['imgMedium'] != "": photo = Photo(id=trail.id, name=trail.name + " photo", lat=trail.lat, lon=trail.lon) photo.url = t['imgMedium'] photos[t['imgMedium']] = photo photo.trail = trails[t['id']] photo.content = getPhotoContents(photo.url) resort.trails.append(trails[t['id']]) resort.photos += trails[t['id']].photos return trails, photos
def test_corrupted(self): p = session.query(Photo).filter_by(filename='bee.jpg').one() assert p self.assertFalse(p.is_corrupted()) p = Photo(base_uri = os.path.join('file://', BASE_PATH, 'tests'), filename = 'bee-corrupted.jpg') self.assertTrue(p.is_corrupted())
def add_photo(self, album_id=''): if request.method == 'POST': album = Album.get(id=album_id) photo = Photo() photo.album = album file = request.files['files'] photo_title, size, photo_path, photo_url, thumb_url, thumb_path = self.gal_man.add_photo(album, file) result = [] result.append({ 'name':photo_title, 'size':size, 'url':photo_url, 'thumbnail_url':thumb_path, "delete_type":"POST", }) photo.title = photo_title photo.photo_path = photo_path photo.thumb_path = thumb_path photo.photo_url = photo_url photo.thumb_url = thumb_url photo.size = size photo.save() return json.dumps(result) else: return 'response'
def new_photo(slide_id): slide = Slide.query.filter_by(id=slide_id).first() if not slide: flash(BAD_KITTY, 'danger') return redirect(url_for('index')) journey = Journey.query.filter_by(id=slide.journey_id, user_id=current_user.id).first() if not journey: flash(BAD_KITTY, 'danger') return redirect(url_for('index')) form = NewPhotoForm(slide_id=slide_id) if form.validate_on_submit(): photo = Photo() tmp = tempfile.NamedTemporaryFile(suffix = '.jpg') form.photo.data.save(tmp) tmp.flush() photo.create(form.data['title'], form.data['description'], slide_id, tmp.name) db.session.add(photo) db.session.commit() flash('Photo added to slide', 'success') return redirect(url_for('edit_slide', slide_id=slide_id)) flash_errors(form) return render_template('new-photo.html', form=form, title='New Photo')
def post(self): if self.get_uploads('image'): upload_files = self.get_uploads('image') blob_info = upload_files[0] else: blob_info = None if self.form.validate(): form = self.form photo = Photo(name=form.name.data, image=blob_info) if (form.lat.data and form.lon.data): photo.location = db.GeoPt(lat=form.lat.data, lon=form.lon.data) photo.put() response = redirect_to('collector-thanks', ) else: form = self.form photo = Photo(name=form.name.data, email=form.email.data, phone=form.phone.data, image=blob_info) photo.put() response = redirect_to('collector', photo=photo.key()) # Clear the response body. response.data = '' return response
def get_photo(self): if "photo" not in self.request.POST: logging.debug("no image uploaded for new item!") return None try: img = self.request.POST.get("photo") img_name = img.filename img_data = img.file.read() img = images.Image(img_data) img.im_feeling_lucky() img.resize(640, 480) png_data = img.execute_transforms(images.PNG) img.resize(200, 140) thumb = img.execute_transforms(images.PNG) photo = Photo(name=img_name, image=png_data, thumb=thumb) return photo.put() except images.BadImageError: self.error(400) self.response.out.write("Sorry, we had a problem processing the image provided.") except images.NotImageError: self.error(400) self.response.out.write( "Sorry, we don't recognize that image format." "We can process JPEG, GIF, PNG, BMP, TIFF, and ICO files." ) except images.LargeImageError: self.error(400) self.response.out.write("Sorry, the image provided was too large for us to process.")
def save_item(item, update_desc=False): baidu_id = item.get('id') if baidu_id is None: return session = DB_Session() photo = session.query(Photo).filter(Photo.baidu_id==baidu_id).first() if not photo: photo = Photo(baidu_id=baidu_id, photo_id=item['photo_id'], image_url = item['image_url'], image_width = item['image_width'], image_height = item['image_height'], thumbnail_url = item['thumbnail_url'], thumbnail_width = item['thumbnail_width'], thumbnail_height = item['thumbnail_height'], thumb_large_url = item['thumb_large_url'], thumb_large_width = item['thumb_large_width'], thumb_large_height = item['thumb_large_height'], from_url = item['from_url'], obj_url = item['obj_url'], desc = item['desc'], image_date = item['date'], insert_date = datetime.datetime.now() ) session.add(photo) session.commit() logging.warn("add one item-%s" % photo.id) elif update_desc: photo.desc = item['desc'] session.commit() logging.warn("update one item-%s" % photo.id) session.close()
def create_photo(file_path): photo_path, width, height = image_utils.fit_and_save(file_path) thumb_path = image_utils.generate_thumbnail(photo_path) photo_path, thumb_path = (relp(rp(p), PARENT_DIR) for p in (photo_path, thumb_path)) photo = Photo(image_path=photo_path, thumbnail_path=thumb_path, width=width, height=height) photo.save() return photo
def post_photo(user, request): yelp_id = request.form.get('yelp_id') if not yelp_id: return {'error': 'Missing yelp_id.'}, HTTP_STATUS_BAD_REQUEST restaurant = yelp_client.get_restaurant(yelp_id) if not restaurant: return {'error': 'Invalid yelp_id'}, HTTP_STATUS_INTERNAL_SERVER_ERROR if 'image' not in request.files: return {'error': 'No image attached!'}, HTTP_STATUS_BAD_REQUEST file = request.files.get('image') try: user_id = user.id photo_url = s3_client.upload_photo(user_id, file) photo = Photo(user_id=user_id, photo_url=photo_url, yelp_id=restaurant.id, restaurant_name=restaurant.name) session.add(photo) session.flush() session.commit() return photo.to_dict(), HTTP_STATUS_OK except S3UploadFailedError as e: logging.error(str(e)) return {'error': 'Failed to upload image!'}, HTTP_STATUS_BAD_REQUEST
def photographer_upload(): # if request method is post if request.method == 'POST': form = PhotoUploadForm(name=request.form.get("name"), file=request.files.get("file")) if form.validate(): # get the photographer id from the user # save the image and link to photographer image_file = form.file.data photo = Photo(name=form.name.data, photographer_id=current_user.photographer.id, file=image_file.read()) image = Image.open(image_file) file_type = image_file.headers.get("Content-Type") photo.add_image_data(*image.size, file_type) # save photo to db session_object = db_session() session_object.add(photo) session_object.commit() # success message flash("Image Uploaded Successfully", "success") return redirect(url_for('dashboard')) else: return render_template('photographer_uploads.html', form=form) # if the request is any other than get return render_template('photographer_uploads.html', form=PhotoUploadForm())
def upload(request): if request.content_length/1000000 > 20: return error_response(400, 'Sorry, but the file must be under 20MB.') # Create photo object in database photo = Photo(datetime.today(), request.POST['file'].filename, request.client_addr, request.content_type, request.content_length) DBSession.add(photo) DBSession.flush() # Save uploaded file input_file = request.POST['file'].file input_file.seek(0) if not os.path.exists('data'): os.makedirs('data') if not os.path.exists('data/uploads'): os.makedirs('data/uploads') upload_path = os.path.join('data', 'uploads', str(photo.id)) with open(upload_path, 'w') as f: shutil.copyfileobj(input_file, f) # Check the content type and rename as appropriate mime = magic.from_file(upload_path, mime=True) if mime not in ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/tiff', 'image/x-tiff']: resp = Response('Sorry, but we can only accept jpg, gif, or png files.') resp.status_code = 400 resp.status_string = '400 Bad Request' return resp extension = {'image/jpeg': '.jpg', 'image/pjpeg': '.jpg', 'image/gif': '.gif', 'image/png': '.png', 'image/tiff': '.tiff', 'image/x-tiff': '.tiff'}[mime] os.rename(upload_path, upload_path + extension) photo.content_type = mime return Response('OK')
class AlbumTest(TestCase): def setUp(self): self.user = User(username='******', email='*****@*****.**', first_name='Sherlock', last_name="Holmes", password='******') self.user.full_clean() self.user.save() self.photo = Photo(owner=self.user, image='images/test.png', name='test', caption='testing') self.photo.clean() self.photo.save() self.tag = Tag(name='test tag', owner=self.user) self.tag.clean() self.tag.save() self.photo.tags.add(self.tag) self.album = Album(owner=self.user, name='test album') self.album.clean() self.album.save() self.album.photos.add(self.photo) def test_id_creation(self): self.assertIsNotNone(self.album.id) def test_owner_entry(self): self.assertEqual(self.album.name, 'test album') def test_name_entry(self): self.assertEqual(self.photo.name, 'test') def test_album_to_photo_association(self): photos = Photo.objects.filter(album=self.album.id) self.assertEqual(photos[0].name, 'test')
def edit(): form = EditForm(g.user.nickname) if request.method == 'POST': avatar_img_file = request.files[form.avatar_img.name] else: avatar_img_file = None if form.validate_on_submit(avatar_img_file): g.user.nickname = form.nickname.data g.user.about_me = form.about_me.data db.session.add(g.user) db.session.commit() if form.avatar_img.data: f = request.files[form.avatar_img.name] pic = Photo(fname = "", timestamp = datetime.utcnow(), owner = g.user) db.session.add(pic) db.session.commit() #try: pic.fname = (str(pic.id)+"."+f.filename.split(".")[-1]) f.save(os.path.join(UPLOAD_IMG_DIR, pic.fname)) g.user.set_avatar(pic) db.session.add(pic) db.session.add(g.user) db.session.commit() flash('Your changes have been saved.', 'info') return redirect(url_for('user', nickname=g.user.nickname)) else: form.nickname.data = g.user.nickname form.about_me.data = g.user.about_me return render_template('edit.html', form = form, user = g.user)
def new_photo(slide_id): slide = Slide.query.filter_by(id=slide_id).first() if not slide: flash(BAD_KITTY, 'danger') return redirect(url_for('index')) journey = Journey.query.filter_by(id=slide.journey_id, user_id=current_user.id).first() if not journey: flash(BAD_KITTY, 'danger') return redirect(url_for('index')) form = NewPhotoForm(slide_id=slide_id) if form.validate_on_submit(): photo = Photo() tmp = tempfile.NamedTemporaryFile(suffix='.jpg') form.photo.data.save(tmp) tmp.flush() photo.create(form.data['title'], form.data['description'], slide_id, tmp.name) db.session.add(photo) db.session.commit() flash('Photo added to slide', 'success') return redirect(url_for('edit_slide', slide_id=slide_id)) flash_errors(form) return render_template('new-photo.html', form=form, title='New Photo')
def upload(): path = os.path.join(Config.UPLOADS_DEFAULT_DEST, str(current_user.id), request.form.get('slug')) path_min = os.path.join(Config.DEFAULT_MIN_DIR, str(current_user.id), request.form.get('slug')) # создаем директорию для фоток, если ее нет if not os.path.isdir(path): os.makedirs(path) # создаем директорию для миниатюр, если ее нет if not os.path.isdir(path_min): os.makedirs(path_min) album = Album.objects(slug=request.form.get('slug', ''), user=current_user.id).get() photos_list = album.photos for img in request.files.getlist("images"): if img.filename: file_path = photos.save(img, folder=path) filename = file_path.split('/')[-1] image = PilImage.open(file_path) exif_data = image.getexif() device = None created = None for tag_id in exif_data: tag = TAGS.get(tag_id, tag_id) data = exif_data.get(tag_id) try: if isinstance(data, bytes): data = data.decode() if f"{tag:25}".find('Model') == 0: device = data if f"{tag:25}".find('DateTimeOriginal') == 0: created = data except: pass ratio = (Config.WIDTH / float(image.size[0])) height = int((float(image.size[1]) * float(ratio))) image = image.resize((Config.WIDTH, height), PIL.Image.ANTIALIAS) file_min_path = image.save(os.path.join(path_min, filename)) photo = Photo() photo.file = filename photo.device = device if created: photo.created = datetime.strptime(created, '%Y:%m:%d %H:%M:%S') photos_list.append(photo) # сортируем фотографии по дате создания в обратном порядке try: photos_list = sorted(photos_list, key=itemgetter('created'), reverse=True) except TypeError: photos_list = sorted(photos_list, key=itemgetter('file')) album.update(photos=photos_list)
def testQueryPhoto(self): photo = Photo() photo.name = "Test Query Photo" photo.id = 50 photo.trailid = 50 self.acc.insertData([photo]) self.assertEqual(self.acc.queryPhoto("Test Query Photo").id, 50) self.assertEqual(self.acc.queryPhoto("Test Query Photo").trailid, 50)
def create_photo(user, image): m = Photo(user=user) if image: image.seek(0) m.save_file(image) m.save() lookedup = Photo.objects.get(id=m.id) return lookedup
def photo_save(request): if request.user.client_photo.count() >= 7: return HttpResponse('Max is 7') avatar = get_or_none(Photo, user=request.user, avatar=True) photo = Photo(user=request.user, photo=request.FILES['file']) if not avatar: photo.avatar = True photo.save() return HttpResponse('Uploaded')
def get(self): user = users.get_current_user() albumName = self.request.get('name') nickname = users.get_current_user().nickname() # Clear all photo data stored in the db query = "Where owner = '%s'" % (user) allPhoto = Photo.gql(query) db.delete(allPhoto) # Get selected album with owner query = "Where albumName = '%s' AND owner ='%s'" % (albumName, nickname) selectedAlbum = Album.gql(query) # Pre-select if album is empty if selectedAlbum[0].albumPhoto == '0': template_values = { 'user': user, 'albumName': albumName, } render_template(self, 'photo.html', template_values) gd_client = gdata.photos.service.PhotosService() photoList = gd_client.GetFeed('/data/feed/api/user/%s/albumid/%s?kind=photo' % (user, selectedAlbum[0].albumID)) # initialize Lock and Queue objects lock = Lock() photoQueue = Queue() for photo in photoList.entry: photoQueue.put(photo) # start consumer for i in range(numConsumer): worker = Thread(target=consumer, args=(photoQueue, selectedAlbum[0].albumPhoto, nickname, lock)) worker.start() # for thread in joinable: # thread.join() photoQueue.join() # All consumer thread are finished, empty photoQueue # with stdout_mutex: print "All done" lock.acquire() time.sleep(1) query = "Where owner = '%s'" % (nickname) allPhoto = Photo.gql(query) print allPhoto.count() template_values = { 'user': user, 'allPhoto': allPhoto, 'albumName': albumName, } lock.release() render_template(self, 'photo.html', template_values)
def create_photo_fixtures(number=40, events_number=100): photos = [[dict( key=photo_keys[i % len(photo_keys)], bibnumbers=f'{i} {i+1} {i+2}', owner=1, event=j+1, ) for i in range(number)] for j in range(events_number)] for photo_set in photos: Photo.insert_many(photo_set).execute()
def create_conversation(user_id, conversation): conversation_type = conversation.get('conversation_type') conversationees_list = conversation.get('conversationees_list') conversationees_list = list(set(conversation.get('conversationees_list',[]))) if conversation_type == conversations_config.get('CONVERSATION_DIRECT_TYPE') and len(conversationees_list) != 2: raise InvalidConversationException('Direct conversations should have 2 conversationees') ct = ConversationType.get(ConversationType.name == conversation_type) c = Conversation() c.conversation_type = ct p_url = conversation.get('picture','') picture = None if p_url: picture = Photo() picture.url = p_url name = conversation.get('name','') cps = [] myself = None for index, conversationee in enumerate(conversationees_list): n = None p = None if conversation_type == 'group': n = name p = picture else: data = get_user_data(index, conversationees_list) n = data[0] p = data[1] cp = ConversationParty() cp.conversation = c cp.name = n cp.user = User.get(User.id==conversationee) cp.picture = p cps.append(cp) if conversationee == user_id: myself = cp with database.transaction(): c.save() if picture: picture.save() for cp in cps: cp.save() return __jsonify_one_conversation(myself)
def setUp(self): ''' Метод начальной инициализации ''' photo = Photo(photo = 'this is a photo, believe me ;)') photo.save() user = User(login='******',password='******',avatarId = photo, rating = 0) user.save() user = User(login='******',password='******',avatarId = photo, rating = 0) user.save()
def savePhoto(self, galleryId, photoId, photoName, photoDescription, photoPosition, file): photo = None if(photoId): photo = Photo.objects.get(id=photoId) else: gid = uuid.uuid1().__str__() gid = gid.replace('-', '') photo = Photo() photo.id = gid photo.name = photoName photo.description = photoDescription photo.position = photoPosition photo.gallery_id = galleryId if(file): photoType = file.name.split('.') photo.type = photoType[1] if photoType.__len__() == 2 else '' destination = open(constant.upload_path + galleryId + '/' + photo.id + '.' + photo.type, 'wb') try: for chunk in file.chunks(): destination.write(chunk) finally: destination.close() photo.save()
def createEvent(sessionId, eventArgs): ''' Метод для создания событий (по сессии и списку аргументов) ''' userId = SessionManager.getUser(sessionId) eName = 'Noname event' eTime = '2012-12-31' eDescription = 'No defenition' photo = Photo.objects.get(pk=1) eEventTypeId = 1 eLatitude = 0 eLongitude = 0 eCountryId = Country.objects.get(pk=1) eCityId = City.objects.get(pk=1) eNamePlace = 'Noname place' if eventArgs.has_key('name'): eName = eventArgs['name'] if eventArgs.has_key('time'): eTime = eventArgs['time'] if eventArgs.has_key('description'): eDescription = eventArgs['description'] if eventArgs.has_key('photo'): photo = Photo(photo=eventArgs['photo']) photo.save() else: photo = Photo.objects.get(pk=1) if eventArgs.has_key('eventTypeId'): eEventTypeId = eventArgs['eventTypeId'] if eventArgs.has_key('longitude'): eLatitude = eventArgs['longitude'] if eventArgs.has_key('latitude'): eLongitude = eventArgs['latitude'] place = Place(cityId=eCityId, countryId=eCountryId, name=eNamePlace, latitude=eLatitude, longitude=eLongitude) place.save() newEvent = Event(creatorId=userId, name=eName, time=eTime, description=eDescription, photoId=photo, eventTypeId_id=eEventTypeId, PlaceId=place) newEvent.save() return newEvent.pk
def save_photo(file, user_id=None, spot_id=None): filename = str(uuid.uuid4()) + "." + file.filename.rsplit('.', 1)[1].lower() if user_id is not None: s3.Bucket(bucket).put_object(Key=filename, Body=file) new_photo = Photo(user_id=user_id, filename=filename) db.session.add(new_photo) if spot_id is not None: s3.Bucket(bucket).put_object(Key=filename, Body=file) new_photo = Photo(spot_id=spot_id, filename=filename) db.session.add(new_photo) db.session.commit()
def create_photo(path, owner, title, access, description): with open('imagr_images/test_data/'+path, 'rb') as f: image = ImageFile(f) photo = Photo( image=image, owner=owner, title=title, access=access, description=description ) photo.save() return photo
def up_photo(): if request.method == 'POST': print('True') img = request.files.get('fileList') print(img.filename) im = misc.imread(img) path = os.path.dirname(__file__) print('g.user is ', g.user.username) if not os.path.exists(path): os.makedirs(path) basepath = os.path.dirname( __file__) + '/static/photo' + '/' + g.user.username print(basepath) if not os.path.exists(basepath): os.makedirs(basepath) #########产生JK序列######### JK = generate_JK(im) #########加密算法######### miwen = jiami(im, np.array(JK)) miwen = Image.fromarray(miwen.astype(np.uint8)) filepath = os.path.join(basepath, img.filename) miwen.save(filepath) photo_exit = Photo.query.filter(Photo.photoname == img.filename).all() usernames = [] for k in photo_exit: usernames.append(k.username) print(usernames) print(g.user.username) if photo_exit is None: photo_new = Photo( username=g.user.username, photoname=img.filename, photopath='http://172.31.102.126:4241/static/photo/' + g.user.username + '/' + img.filename) db.session.add(photo_new) db.session.commit() elif g.user.username not in usernames: photo_new = Photo( username=g.user.username, photoname=img.filename, photopath='http://172.31.102.126:4241/static/photo/' + g.user.username + '/' + img.filename) db.session.add(photo_new) db.session.commit() return jsonify(g.user.username, img.filename) # for file in request.files.getlist('file'): # 这里改动以存储多份文件 # if file and allowed_file(file.filename): # filename = secure_filename(file.filename) # file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) else: return render_template('up_photo.html')
def setUp(self): ''' Метод начальной инициализации ''' photo = Photo(photo='this is a photo, believe me ;)') photo.save() user = User(login='******', password='******', avatarId=photo, rating=0) user.save() user = User(login='******', password='******', avatarId=photo, rating=0) user.save()
def post(self): try: upload = self.get_uploads('file') blob = upload[0] description = self.request.get('description'); title = self.request.get('title'); photo = Photo(blobKey=str(blob.key()), description=description, title=title) photo.put() competition = Competition(photoKey=photo.key(), dateCreated=datetime.datetime.now()) competition.put(); self.redirect("/competitions/latest") except: self.redirect("/upload-failure")
def photo_create(post_id): form = PhotoForm() form.post_id.data = post_id if form.validate_on_submit(): files = request.files.getlist('file') for file in files: photo = Photo() photo.upload(file, post_id) return redirect(url_for('house.article_show', id=post_id)) return render_template('photo_create.html', form=form)
def post(self): if self.get_uploads('image'): upload_files = self.get_uploads('image') blob_info = upload_files[0] else: blob_info=None if self.form.validate(): form=self.form photo=Photo(name=form.name.data, image=blob_info ) if (form.lat.data and form.lon.data): photo.location=db.GeoPt(lat=form.lat.data,lon= form.lon.data) photo.put() response = redirect_to('collector-thanks',) else: form=self.form photo=Photo(name=form.name.data, email=form.email.data, phone=form.phone.data, image=blob_info ) photo.put() response = redirect_to('collector',photo=photo.key()) # Clear the response body. response.data = '' return response
def test_create_photo(self): """Create a photo and assert that its fields appear as expected.""" photo = Photo( author=self.u, description='A Photo', image=self.image ) photo.full_clean() photo.save() self.assertIsInstance(photo, Photo) self.assertIsInstance(photo.date_created, datetime) self.assertIsInstance(photo.date_modified, datetime) self.assertEqual(photo.description, 'A Photo') self.assertEqual(photo.author, self.u)
def index(request): "Obtains the attachment and saves it to the disk" if request.method == 'POST': form = AttachmentForm(request.POST, request.FILES) if form.is_valid(): f = form.cleaned_data['image'] foto = Photo() foto.image.save(f.name, f) foto.comments = form.cleaned_data['comments'] foto.save() return HttpResponseRedirect('/') else: form = AttachmentForm() fotos = Photo.objects.all() return render_to_response('index.html', {'form':form, 'fotos': fotos})
def render_photo(self, id): photo = Photo.get_by_id(int(id)) blobKey = photo.blobKey if blobKey: blobinfo = blobstore.get(blobKey) if blobinfo: aspect = 'h' img = images.Image(blob_key=blobKey) img.rotate(180) thumbnail = img.execute_transforms(output_encoding=images.JPEG) if img.width > img.height: pass else: aspect = 'v' img = images.Image(blob_key=blobKey) if aspect == 'h': img.resize(width=505) else: img.resize(width=355) thumbnail = img.execute_transforms(output_encoding=images.JPEG) return thumbnail return self.error(404)
def list_files(): logger.debug('list files') photos = Photo.all() logger.debug(photos) context = {'photos': photos} template = j2env.get_template('templates/list.html') return template.render(context)
def photo(request, owner, nb): try: photo = Photo.get(owner, nb) owner = User.get(owner) return render(request, 'photo.html', {'owner': owner, 'photo': photo}) except (Photo.DoesNotExist, User.DoesNotExist): return HttpResponseRedirect('/')
def get(self, id): photo = Photo.gql("WHERE id = :1", id).get() comments = sorted(photo.comment_set) self.render_html("photo_comments", { 'photo': photo, 'comments': comments })
def run(): redis_client = get_redis_client() redis_client.delete(REDIS_KEY['USER_LIKED_COUNT']) redis_client.delete(REDIS_KEY['USER_LIKES_COUNT']) redis_client.delete(REDIS_KEY['USER_PHOTO_COUNT']) photos = Photo().select(['id', 'user_id', 'likes_count']).where('status', '=', 0).findall(limit=1000000) for photo in progress.bar(photos): current_liked_count = redis_client.hget(REDIS_KEY['USER_LIKED_COUNT'], photo.user_id) or 0 redis_client.hset(REDIS_KEY['USER_LIKED_COUNT'], photo.user_id, int(current_liked_count) + int(photo.likes_count)) current_photo_count = redis_client.hget(REDIS_KEY['USER_PHOTO_COUNT'], photo.user_id) or 0 redis_client.hset(REDIS_KEY['USER_PHOTO_COUNT'], photo.user_id, int(current_photo_count) + 1) photo_like = Photo_Like().findall_by_photo_id(photo.id) for item in photo_like: current_likes_count = redis_client.hget( REDIS_KEY['USER_LIKES_COUNT'], item.user_id) or 0 redis_client.hset(REDIS_KEY['USER_LIKES_COUNT'], item.user_id, int(current_likes_count) + 1)
def album_detail_page(album_id=0, page=0): if page <= 0: abort(404) album = model_to_dict(Album.get(Album.id == album_id)) if not album: abort(404) total_page = int(math.ceil(album["count"] * 1.0 / config.ITEMS_PER_PAGE)) extra = entry_comments_api(entry_id=album_id) photos = list( Photo.select() .where(Photo.album_id == album_id) .order_by(Photo.pos) .paginate(page, config.ITEMS_PER_PAGE) .dicts() ) return render_template( "album.html", album=album, page=page, total_page=total_page, photos=photos, **extra )
def add_media_item(media_type): logger.info("add_media_item %s" % media_type) file = request.files['file'] filename = file.filename group_id = request.values.get("group_id") album_id = request.values.get("album_id") secured_filename = secure_filename(filename) file_path = os.path.join(config.UPLOAD_FOLDER, secured_filename) file.save(file_path) logger.info("save file %s to file path %s" % (filename, file_path)) # file_url = url_for('uploaded_file', filename=filename) file_url = "/static/upload/" + secured_filename photo = Photo(album_id=album_id, group_id=group_id, url=file_url, media_type=media_type, name=filename) db.session.add(photo) db.session.commit() data = { "photo_id": photo.id, "album_id": album_id, "group_id": group_id, "file_url": file_url } return make_response(jsonify(data))
class TestPhotoModel(ut.TestCase): def setUp(self): self.photo = Photo() self.photo.id_setting() def test_id_not_None(self): self.assertIsNotNone(self.photo.id) def test_randomness_of_id(self): self.photo2 = Photo() self.photo2.id_setting() self.assertNotEqual(self.photo.id, self.photo2.id) def test_image_path(self): path = _get_image_path(self.photo, 'sample.jpg') self.assertEqual(path, 'photo/photos/' + self.photo.id + '.jpg')
def delete_photo(photo_id): logger.debug('delete photo id: %d' % photo_id) photo = Photo.get_by_id(photo_id) logger.debug('delete photo name: %s' % photo.name) db.delete(photo) response = make_response('OK', 200) return response
def get_photo(photo_id): logger.debug('get photo id: %d' % photo_id) photo = Photo.get_by_id(photo_id) logger.debug('found photo name: %s' % photo.name) response = make_response(photo.thumbnail) response.headers['Content-Type'] = 'image/jpeg' return response
def index(request): # return HttpResponse("Hello, world. You're at the photoslideshow app.") #latest_photos = Photo.objects.all()[:5] #output = ', '.join([p.url for p in latest_photos]) #output = '' xmlphotoset = get_photos_for_vivid_festival() photoset = xmlphotoset.find('photoset') #print(photoset.attrib) latest_photos = [] for photo in photoset.findall('photo'): photo_id = photo.attrib['id'] photo_title = photo.attrib['title'] photo_url = get_photo_url_large(photo_id) #photo_created_date = '' p = Photo(title=photo_title, url=photo_url, created_date='') latest_photos.append(p) #for p in latest_photos: #new_image = '<img src="' + p.url + '" + alt="' + p.title + '" > <br/>' #output += new_image #return HttpResponse(output) return render(request, 'display_photo.html', { 'photos': latest_photos, 'firstphoto': latest_photos[0] })
def create_photo(request): """ Gestiona la creación de una nueva foto :param request: objeto request :return: objeto response """ new_photo = None if request.method == 'POST': # si le hemos dado al boton crear, vamos a validar el formulario y a guardar la foto photo_with_user = Photo(owner=request.user) # creamos foto para el usuario autenticado form = PhotoForm(request.POST, instance=photo_with_user) # Le indicamos que en lugar de instanciarse una foto propio, # use new_photo que tiene ya asignado un usuario if form.is_valid(): new_photo = form.save() # guardamos la foto en la base de datos form = PhotoForm() #para que nos borre la info que ya habíamos metido en el formulario else: # si no, creamos un formulario vacio form = PhotoForm() context = { 'form' : form, 'photo' : new_photo } return render(request, 'photos/create_photo.html', context)
def api_search(request): query = request.GET.get('q', '').strip() # uodpornienie na "sphinx injection" - pozwala tylko na proste query query = re.sub('[{0}]'.format(string.punctuation), '', query) limit = min(settings.MAX_LIMIT, int(request.GET.get('l', settings.MAX_LIMIT))) offset = int(request.GET.get('o', 0)) if limit <= 0 or offset < 0: ret = json.dumps({'error' : 'Incorrect limit or offset'}) else: if query: photos, totalFound = Photo.find_by_desc(query, limit, offset) ret = { 'totalFound' : totalFound, 'query' : query, 'limit' : limit, 'offset' : offset, 'photos' : [{ 'thumbnailFile': '/thumbnails/%s,%s-160x160.jpg' % (p.owner, p.nb), 'photoPage': '/photo/%s,%s' % (p.owner, p.nb), 'description': p.desc, } for p in photos]} else: ret = {'error' : 'Empty query'} return HttpResponse(json.dumps(ret, ensure_ascii=False), content_type='application/json')
def img_save(self): """ Tests that we can save a Photo. """ # self.failUnlessEqual(1 + 1, 2) from PIL import Image from models import Photo im = Image.open('P1020515.JPG') photo = Photo() photo.img=im photo.url='http://go00gle.com' photo.save() self.failUnlessEqual(im,photo.img) self.failUnlessEqual(photo.url, 'http://google.com')
def get_file(file_id): logger.debug('find file id: %d' % file_id) file = Photo.get_by_id(file_id) logger.debug(file.name) response = make_response(file.full_image) response.headers['Content-Disposition'] = "attachment; filename=%s" % file.name return response
def __init__(self): t = datetime.datetime.now() - datetime.timedelta(hours=4) s = Subject().get_current().key().id() for img in ( Photo.all().filter("subject_id =", s).filter("is_blocked =", False).filter("date_updated <", t).fetch(10) ): self.fetch_img(img.instagram_id)
def album_detail_page(album_id=0, page=0): if page <= 0: abort(404) album = model_to_dict(Album.get(Album.id == album_id)) if not album: abort(404) total_page = int(math.ceil(album['count'] * 1.0 / config.ITEMS_PER_PAGE)) comments = list(Comment.select().where( Comment.entry_id == album_id).order_by(Comment.t).dicts()) likes = list(Like.select().where(Like.entry_id == album_id).dicts()) uids = list( set([c['authorId'] for c in comments] + [l['uid'] for l in likes])) users = dict([(u['uid'], { 'name': u['name'], 'headPic': u['headPic'] }) for u in User.select().where(User.uid.in_(uids)).dicts()]) photos = list(Photo.select().where(Photo.album_id == album_id).order_by( Photo.pos).paginate(page, config.ITEMS_PER_PAGE).dicts()) return render_template("album.html", album=album, page=page, total_page=total_page, comments=comments, likes=likes, users=users, photos=photos)
def photo_delete(photo_id): try: photo = Photo.get(Photo.photo_id == photo_id) photo.delete_instance() redirect('/gallery_add') except DoesNotExist: abort(404)
def build_photo(id, line): elements = line.split() orientation = elements[0] tags = set(elements[2:2 + int(elements[1])]) return Photo(id=id, orientation=orientation, tags=tags)
def post(self, stream_id): stream_key = ndb.Key('Stream', int(stream_id)) img_field = self.request.POST.get('image') uploaded_file_content = img_field.file.read() uploaded_file_type = img_field.type # Process the image by rotating it 0 degress in order to fix # the image orientation based on EXIF data. process_image = images.Image(image_data=uploaded_file_content) process_image.set_correct_orientation(images.CORRECT_ORIENTATION) process_image.rotate(0) process_image_content = process_image.execute_transforms( parse_source_metadata=True) logging.info("image metadata {0}".format( process_image.get_original_metadata())) # If the processed image actually was rotated because of EXIF orientation # we use the processed image, otherwise we use the original file content. if ('Orientation' in process_image.get_original_metadata() and process_image.get_original_metadata()['Orientation'] in [3, 6, 8]): image_content_to_save = process_image_content logging.info('using processed image') else: image_content_to_save = uploaded_file_content logging.info('using original image') thumbnail = images.resize(image_content_to_save, 200, 200) # even if we process the file we calc the hash using original upload content. checksum = base64.urlsafe_b64encode( hashlib.sha256(uploaded_file_content).digest()) logging.info("sha256: {0}".format(checksum)) write_photo_to_storage(users.get_current_user().user_id(), checksum, 'main', uploaded_file_type, image_content_to_save) write_photo_to_storage(users.get_current_user().user_id(), checksum, 'thumbnail', uploaded_file_type, thumbnail) photo = Photo(parent=stream_key, created_by_user_id=users.get_current_user().user_id(), sha256=checksum) photo.put() self.response.out.write("ok")
def photo_detail_page(photo_id=0): photo = model_to_dict(Photo.get(Photo.id == photo_id)) if not photo: abort(404) extra = entry_comments_api(entry_id=photo_id) return render_template("photo.html", photo=photo, **extra)
def search(request): query = request.GET.get('q', '').strip() if query: photos, _ = Photo.find_by_desc(query, 30, 0) else: photos = None return render(request, 'search.html', {'query': query, 'photos': photos})
def save_images(offerId, images): from urllib.request import urlretrieve for i in images: from models import Photo im = Photo(offerId=offerId, url=i) # named params because no Photo.__init__ path = "images/{0}/{1}.jpg".format(offerId, im.id) urlretrieve(i, path)
def remove_photo(self, album_id=''): if request.method == 'POST': form = request.form for v in form.itervalues(): try: photo = Photo.get(id=v) photo.delete_instance() except DoesNotExist, e: print '%s' % e
async def api_create_photo(request, *, name, url): check_admin(request) #检查request对象身上是否绑定了user if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not url or not url.strip(): raise APIValueError('url', 'summary cannot be empty') photo = Photo(user_id=request.__user__.id, user_name=request.__user__.name, name=name.strip(), url=url.strip()) await photo.save() return photo