def test_post_photo(self): # create four users u1 = User(name='John Tan', email='*****@*****.**') u2 = User(name='Susan Tay', email='*****@*****.**') u3 = User(name='Mary Mee', email='*****@*****.**') u4 = User(name='David Malan', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) # create and all all users to a journey journey = Journey(id="Fun Tiempo") journey.add_user(u1) journey.add_user(u2) journey.add_user(u3) journey.add_user(u4) db.session.add(journey) db.session.commit() # create four photos p1 = Photo(longitude=0.123, latitude=4.567, journey__id="Fun Tiempo") p2 = Photo(longitude=0.123, latitude=4.567, journey__id="Fun Tiempo") p3 = Photo(longitude=0.123, latitude=4.567, journey__id="Fun Tiempo") p4 = Photo(longitude=0.123, latitude=4.567, journey__id="Fun Tiempo") db.session.add_all([p1, p2, p3, p4]) db.session.commit() # test relationships self.assertEqual(journey.photos, [p1, p2, p3, p4]) self.assertEqual(u1.journeys.first(), journey) self.assertEqual(u2.journeys.first().photos, [p1, p2, p3, p4])
def photos(): if request.method == "POST": filename = str(request.data.get('filename', '')) if filename: photo = Photo(filename=filename) photo.save() response = jsonify({ 'id': photo.id, 'filename': photo.filename, 'date_created': photo.date_created, 'date_modified': photo.date_modified }) response.status_code = 201 return response else: # GET photos = Photo.get_all() results = [] for photo in photos: obj = { 'id': photo.id, 'filename': photo.filename, 'date_created': photo.date_created, 'date_modified': photo.date_modified } results.append(obj) response = jsonify(results) response.status_code = 200 return response
def change_profile_details(): """Respond to existing user's request to change their profile details.""" user_instance = current_user form = ChangeProfileForm(obj=user_instance) if request.method == 'POST': if form.validate_on_submit(): form.populate_obj(user_instance) db.session.add(user_instance) if request.files['photo']: image_filename = images.save(request.files['photo']) image_url = images.url(image_filename) picture_photo = Photo.query.filter_by(user_id=current_user.id).first() if not picture_photo: picture_photo = Photo( image_filename=image_filename, image_url=image_url, user_id=current_user.id, ) else: picture_photo.image_filename = image_filename picture_photo.image_url = image_url db.session.add(picture_photo) db.session.commit() flash('You have successfully updated your profile', 'success') return redirect(url_for('account.change_profile_details')) else: flash('Unsuccessful.', 'warning') return render_template('account/manage.html', form=form)
def new_photo(id): try: form = UploadPhotoForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): key_list = request.files.keys() if request.files: if "pic_url" in key_list: new_image_data = request.files["pic_url"] new_image_key = f"photos/{uuid.uuid4()}_{new_image_data.filename}" # new_image_key = f"photos/{id}/{uuid.uuid4()}_{new_image_data.filename}" client.put_object(Body=new_image_data, Bucket="kafei", Key=new_image_key, ContentType=new_image_data.mimetype, ACL="public-read") photo = Photo( pic_url=f"https://kafei.s3-us-west-1.amazonaws.com/{new_image_key}", user_id=id ) db.session.add(photo) db.session.commit() return photo.to_dict() except Exception as error: return jsonify(error=repr(error))
def add_gallery(): form = GalleryForm() if form.validate_on_submit(): if request.files.getlist('photos'): ps = [] for file in request.files.getlist('photos'): if file and allowed_file(file.filename): filename = secure_filename(file.filename) extension = filename.rsplit('.', 1)[1].lower() photo = Photo(extension=extension) photo.save() ps.append(photo) unified_filename = str(photo.id) + '.' + extension f = file try: picture_handler(f, unified_filename) except: print("picture file may not be updated") flash('New picture uploaded!') gallery = Gallery(name=form.name.data, description=form.description.data, photos=ps) gallery.save() return redirect(url_for('main.galleries')) return render_template('admin/add_gallery.html', title='Create Gallery', form=form)
def setUp(self): app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" db.create_all() self.client = app.test_client() p1 = Photo("Test1", 123456, 0, 'test1.jpg') p2 = Photo("Test2", 999123, 1, 'test2.jpg') db.session.add_all([p1, p2]) db.session.commit()
def test_parse_exif(self): p1 = Photo.parse_exif(os.path.join(data_path, '1.jpg')) self.assertTrue(p1[0]) self.assertEquals(p1[1], '2019_11_02') self.assertEquals(p1[2], '18_26_44') p2 = Photo.parse_exif(os.path.join(data_path, '2.jpg')) self.assertFalse(p2[0]) self.assertEquals(p2[1], 'photos') self.assertEquals(p2[2], '2.jpg')
def upload(): file = request.files['upload'] photo = Photo() path = app.config["UPLOAD_FOLDER"] + file.filename photo.src = path file.save("app/" + path) db.session.add(photo) db.session.commit() result = {"upload": True, "url": path, "error": False} return json.dumps(result)
def test_one_year_paginator(self): photo = Photo() photo.created_time = date(2012, 02, 29) db.session.add(photo) db.session.commit() self.assertIn(photo, db.session) # This should only run once since the db only has 1 year initially pagination = Pagination(2012) self.assertEqual(1, len(list(pagination.iter_pages())))
def test_day_paginator_two_dates(self): # Start first_photo = Photo() first_photo.created_time = date(2013, 03, 01) db.session.add(first_photo) db.session.commit() self.assertIn(first_photo, db.session) # End second_photo = Photo() second_photo.created_time = date(2013, 03, 15) db.session.add(second_photo) db.session.commit() self.assertIn(second_photo, db.session) # Create day pagination pagination = Pagination(2013, 03, 01) self.assertEqual(1, pagination.page) self.assertEqual(15, pagination.pages) self.assertFalse(pagination.has_prev) self.assertTrue(pagination.has_next) # Create month pagination pagination = Pagination(2013, 03) self.assertEqual(3, pagination.page) self.assertEqual(1, pagination.pages) self.assertFalse(pagination.has_prev) self.assertFalse(pagination.has_next) # Create year pagination pagination = Pagination(2013) self.assertEqual(2013, pagination.page) self.assertEqual(1, pagination.pages) self.assertFalse(pagination.has_prev) self.assertFalse(pagination.has_next) # Widen range second_photo.created_time = date(2013, 03, 31) db.session.commit() pagination = Pagination(2013, 03, 01) self.assertEqual(1, pagination.page) self.assertEqual(31, pagination.pages) self.assertFalse(pagination.has_prev) self.assertTrue(pagination.has_next)
def change_profile_details(): website_settings = MSettings.query.first() """Respond to existing user's request to change their profile details.""" user_instance = current_user form = ChangeProfileForm(obj=user_instance) choices = [('0', "No Recruiter")] + [ ('{}'.format(user.id), user.full_name) for user in User.query.filter_by(profession='Recruiter').all() ] form.recruiter.choices = choices form.recruiter.process_data(form.recruiter.data) if request.method == 'GET' and ( user_instance.profession, user_instance.profession) not in form.profession.choices: form.profession.default = 'OTHER SPECIFY' form.profession.process_data(form.profession.default) form.custom_profession.process_data(user_instance.profession) if request.method == 'GET': form.recruiter.process_data(user_instance.recruiter_id) if request.method == 'POST': if form.validate_on_submit(): profession = form.profession.data if form.profession.data != 'OTHER SPECIFY' else form.custom_profession.data recruiter_id = None if form.profession.data == 'Recruiter' or form.recruiter.data == '0' else form.recruiter.data del form.recruiter form.populate_obj(user_instance) user_instance.profession = profession user_instance.recruiter_id = recruiter_id db.session.add(user_instance) if request.files['photo']: image_filename = images.save(request.files['photo']) image_url = images.url(image_filename) picture_photo = Photo.query.filter_by( user_id=current_user.id).first() if not picture_photo: picture_photo = Photo( image_filename=image_filename, image_url=image_url, user_id=current_user.id, ) else: picture_photo.image_filename = image_filename picture_photo.image_url = image_url db.session.add(picture_photo) db.session.commit() flash('You have successfully updated your profile', 'success') return redirect(url_for('account.change_profile_details')) else: flash('Unsuccessful.', 'warning') return render_template('account/manage.html', website_settings=website_settings, form=form)
def get_photo_info(date_, time_, counterPart, username): """ get the information assciated with a given photo name """ if username == "": session['username'] = "******" #print("testing") logger.error("In 'get_photo_info' function, error occurred") if username == "UnitTester": try: photoInfo = Photo.objects(staffName=username) return photoInfo except Exception as e: #print("error: ", e) logger.error("In 'get_photo_info' function, error occurred: ", e) return None if not counterPart: if utils.check_if_staff(username, False): try: photoInfo = Photo.objects(date=date_, time=time_, staffName=username) except Exception as e: #print("error: ", e) logger.error("In 'get_photo_info' function, error occurred: ", e) return None else: try: photoInfo = TenantPhoto.objects(date=date_, time=time_, tenantName=username) except Exception as e: #print("error: ", e) logger.error("In 'get_photo_info' function, error occurred: ", e) return None else: if utils.check_if_staff(username, False): try: photoInfo = TenantPhoto.objects(staffName=username, date=date_, time=time_) except Exception as e: #print("error: ", e) logger.error("In 'get_photo_info' function, error occurred: ", e) return None else: try: photoInfo = Photo.objects(tenantName=username, date=date_, time=time_) except Exception as e: #print("error: ", e) logger.error("In 'get_photo_info' function, error occurred: ", e) return None return photoInfo
def save_photo(): filename = datetime.now().strftime("%Y%m%d-%H.%M.%S") + ".jpg" file_url = os.path.join(current_app.config['GALLERY_ROOT_DIR'], filename) try: p = Photo(filename=filename, file_path=file_url) db.session.add(p) db.session.commit() p.save_photo() flash('Image was saved as: ' + filename, 'success') except URLError as e: flash('Error: {0}'.format(str(e.errno)), 'warning') return redirect(url_for('main.index')) return redirect(url_for('webcam.photo'))
def add_pokemons(): try: pkmn = Category.query.filter_by(name="pokemon").first() or Category(name="pokemon") db.session.add(pkmn) f = open('app/data/pokemon_data', 'r') for line in f: v = json.loads(line) # 編號、中文、日文、英文 seq = v['seq'] e = v['english'].lower().strip() c = v['chinese'].strip() if Term.query.filter_by(english=e).first(): pass else: # print("%s, %s" % (c, e)) term = Term(english=e, chinese=c, hit_counts=0) db.session.add(term) term = Term.query.filter_by(english=e, chinese=c).first() photo = Photo.query.filter_by(term=term).first() if photo is not None: if v['image'] is not None: photo.url = "http:" + v['image'] else: print("Warning for " + v['seq'] + ": " + v['chinese']) else: photo = Photo(term=term) if v['image'] is not None: photo.url = "http:" + v['image'] else: print("Warning for " + v['seq'] + ": " + v['chinese']) db.session.add(photo) if pkmn not in term.categories.all(): term.categories.append(pkmn) desc = v['desc'] if desc is not None: d = Description.query.filter_by(term=term).first() or Description(term=term, content=desc, subheading="習性") db.session.add(d) db.session.commit() except Exception as e: print(e) pass
def take(self, request): filename = '%s.jpg' % datetime.now().strftime('%Y%m%d%H%M%S%f') Camera.initialize() Camera.camera.capture(os.path.join( settings.MEDIA_ROOT, filename), quality=100 ) photo = Photo() photo.name = filename photo.save() return Response(PhotoSerializer(photo).data)
def upload_image(): if "image" not in request.files: return {"errors": "image required"}, 400 image = request.files["file"] if not allowed_file(image.filename): return {"errors": "file type not permitted"}, 400 image.filename = get_unique_filename(image.filename) upload = upload_file_to_s3(image) if "url" not in upload: # if the dictionary doesn't have a url key # it means that there was an error when we tried to upload # so we send back that error message return upload, 400 url = upload["url"] # flask_login allows us to get the current user from the request new_image = Photo(user=current_user, url=url) db.session.add(new_image) db.session.commit() return {"url": url}
def new_photo(): data = request.json try: photo = Photo( user_id=data['userId'], entry_id=data['entryId'], photos_url=data['photosUrl'] ) db.session.add(photo) db.session.commit() return {'photo': photo.to_dict()} except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while creating the picture']}, 500
def get_data(tableName): mapping = { 'User': 0, 'Photo': 1, 'TenantPhoto': 2, 'PhotoNotification': 3, 'PhotoNotificationFromTenant': 4, 'Audit_FB': 5, 'Audit_non_FB': 6, 'Covid_Compliance': 7 } case = mapping.get(tableName, -1) res = None if case == 0: res = User.objects() elif case == 1: res = Photo.objects() elif case == 2: res = TenantPhoto.objects() elif case == 3: res = PhotoNotification.objects() elif case == 4: res = PhotoNotificationFromTenant.objects() elif case == 5: res = Audit_FB.objects() elif case == 6: res = Audit_non_FB.objects() elif case == 7: res = Covid_Compliance.objects() if case != -1: logger.info("admin selected table: %s", tableName)
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 upload_photo(): if current_user.email not in current_app.config['ADMINS']: flash("You are not authorized to access this page.") return redirect(url_for('main.index')) form = UploadPhotoForm() if form.validate_on_submit(): f = form.upload.data if not allowed_image_file(f.filename): flash("Invalid file type") return redirect(url_for("media.upload_photo")) filename = secure_filename(f.filename) f.save( os.path.join(current_app.config['UPLOAD_FOLDER'], 'photos', filename)) photo = Photo(title=form.title.data, filename=filename) db.session.add(photo) db.session.commit() flash("Photo uploaded") return redirect(url_for('media.gallery')) return render_template('media/upload_photo.html', title="Upload Photo", form=form)
def save_file(message): with app.app_context(): try: if message.document: file_info = bot.get_file(message.document.file_id) file_name = message.document.file_name else: file_info = bot.get_file(message.photo[1].file_id) file_name = file_info.file_path.replace("/", "_") file_id = file_info.file_id self.l.info( '{0} {1} {2} downloading'.format(message.message_id, file_id, file_name)) chat_name = message.chat.title if chat_name: downloaded_file = bot.download_file(file_info.file_path) local_path = self.download_f + "/" + file_id + "_" + file_name with open(local_path, 'w+b') as new_file: new_file.write(downloaded_file) photo = Photo(local_path, file_name, message) if not upload_photo(photo, local_path, chat_name): bot.delete_message(photo.chat_id, photo.msg_id) text = "{0} дубликат".format(photo.yd_filename) self.l.info( '{0} {1} {2} duplicate'.format(message.message_id, file_id, file_name)) bot.send_message(photo.chat_id, text) except ApiException as ae: self.l.error('{0}'.format(ae)) if "file is too big" in ae.args[0]: bot.reply_to(message, "Файл слишком большой. Залейте вручную") except BaseException as e: self.l.error('{0}'.format(e)) bot.reply_to(message, "Файл не скачался. Повторите")
def get_business(self, yelp_id): headers = { "content-type": "application/x-www-form-urlencoded", "authorization": "Bearer " + self.access_token } r = None try: r = requests.get("https://api.yelp.com/v3/businesses/%s" % yelp_id, headers=headers) r = json.loads(r.text) except Exception as e: print("[Yelp API Error] " + e) raise e location = Location.query.filter_by(yelp_id=yelp_id).first() if location == None: name = r.get('name', None) phone = r.get('phone', None) address = " ".join(r['location'].get('display_address', [])) open_hours = json.dumps(r.get('hours', {})) yelp_url = r.get('url', None) location = Location(name=name, phone=phone, address=address, open_hours=open_hours, yelp_url=yelp_url, yelp_id=yelp_id) db.session.add(location) photos = r['photos'] for url in photos: print("Adding photo [%s] for {%s}" % (url, name)) photo = Photo(url=url, location=location) db.session.add(photo) db.session.commit()
def fake_photo(count=30): # photo upload_path = current_app.config['ALBUM_WALL_UPLOAD_PATH'] for i in range(count): print i filename = "random_%d.jpg" % i r = lambda: random.randint(128, 255) img = Image.new(mode="RGB", size=(800, 800), color=(r(), r(), r())) img.save(os.path.join(upload_path, filename)) photo = Photo(description=fake.text(), filename=filename, filename_m=filename, filename_s=filename, author=User.query.get( random.randint(1, User.query.count())), timestamp=fake.date_time_this_year()) # tag for j in range(random.randint(1, 5)): tag = Tag.query.get(random.randint(1, Tag.query.count())) if tag not in photo.tags: photo.tags.append(tag) db.session.add(photo) db.session.commit()
def photo(): photo_id = request.args.get('id') photo = Photo.fetch_by_id(photo_id) metadata_exists = "False" taken_str = "Unknown Year" if photo.taken: taken_str = photo.taken.strftime("%Y") metadata_exists = "True" if photo.taken_lat: metadata_exists = "True" photo_dict = { "id": photo.id, "lat": photo.taken_lat, "lng": photo.taken_lon, "taken": photo.taken_str, "title": photo.title, "url": "https://res.cloudinary.com/dixpjmvss/image/upload/" + photo.pic, "collection": photo.collection_id, "thumbnail": "https://res.cloudinary.com/dixpjmvss/image/upload/" + photo.pic } photo_json = json.dumps(photo_dict) loaded_photo = json.loads(photo_json) return render_template('photo.html', photo=loaded_photo, metadata=metadata_exists)
def upload( yd, log, photo, local_path, chat_title, ): uploaded = False with open(local_path, "rb") as f: if not Chat.is_exists(photo.chat_id): try: Chat.save_to_db(photo.chat_id, chat_title) except BaseException as e: log.error('{0}'.format(e)) yd_path = photo.get_yd_path(yd) if not yd.exists(yd_path): start = time.time() yd.upload(f, yd_path) end = time.time() log.info("YD uploaded: {0} ({1}s)".format( yd_path, str(end - start))) if not Photo.is_exists(photo.chat_id, local_path): db.session.add(photo) db.session.commit() log.info("DB added: " + yd_path) uploaded = True os.remove(local_path) return uploaded
def create(good_name, good_price, good_weight, good_number, category_id, photos, good_desc, attributes, hot_number, good_state, is_promote): if Good.query.filter(or_(Good.good_name == good_name)).first(): return ValidationErrorResult(message='Good已存在') good = Good(good_name=good_name, good_state=good_state, good_price=good_price, good_number=good_number, good_weight=good_weight, good_desc=good_desc, hot_number=hot_number, is_promote=is_promote) category = Category.query.filter(Category.id == category_id).one() if category: category.goods.append(good) good.category_id = category_id if photos: for photo in photos: ph = Photo(photo_name=photo['photo_name'], photo_url=photo['photo_url']) good.photos.append(ph) if attributes: for attribute in attributes: attr = Attribute.query.filter( Attribute.id == attribute['id']).one() if attr: attr.attribute_values = attribute['attribute_values'] db.session.add(good) db.session.flush() return jsonify(schemas.good_schema.dump(good)), 201
def personal_upload_file(): if request.method == 'POST': file = request.files['file'] title = request.form['title'] content = request.form['content'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) #filename=file.filename #file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)) file.save(os.path.join(current_app.root_path, current_app.config['UPLOAD_FOLDER'], str(Time.strftime(ISOTIMEFORMAT))+filename)) from PIL import Image img = Image.open(os.path.join(current_app.root_path, current_app.config['UPLOAD_FOLDER'], str(Time.strftime(ISOTIMEFORMAT))+filename)) img.resize((400,400), Image.ANTIALIAS).save(os.path.join(current_app.root_path, current_app.config['UPLOAD_FOLDER'], str(Time.strftime(ISOTIMEFORMAT))+filename)) photo = Photo(address=os.path.join('uploads/', str(Time.strftime(ISOTIMEFORMAT))+filename), name=title, content = content, time = None, owner_id=current_user.id ) db.session.add(photo) db.session.commit() flash('upload successful!') p = Photo.query.filter_by(owner_id=current_user.id).all() pic_list = [(i.name,i.content,i.address) for i in p] return render_template('personal.html', pic_list=pic_list)
def add_photo(): form = PhotoForm() if request.method == 'POST' and form.validate_on_submit(): form_title = request.form.get('title').capitalize() form_description = request.form.get('description') form_url = request.form.get('url') form_category = request.form.get('category') photo = Photo.query.filter(Photo.title == form_title).first_or_404() category_id = Category.query.filter( Category.name == form_category).first_or_404() if not (photo): new_photo = Photo(title=form_title, slug=form_title, description=form_description, url=form_url, category=category_id, author_id=current_user.user_id) db.session.add(new_photo) db.session.commit() return redirect('/') else: flash("Фотография с таким названием уже существует") return render_template('photos/add_photo.html', form=form)
def populate_db(): # Provider password = encrypt_password('password') p = Provider( user=ud.create_user(email="*****@*****.**", password=password)) p.business_name = 'Sparky\'s' p.user.confirmed_at = datetime.date.today() p.address.street_1 = '403 South Second' p.address.city = 'Clarksville' p.address.state = 'TN' p.address.zip_code = 37040 p.menus[0].menu_items.append( MenuItem(name="Haircut", price="25", description="We cut your hair")) p.menus[0].menu_items.append( MenuItem(name="Line out", price="10", description="A quick line out")) p.menus[0].menu_items.append( MenuItem(name="Shave", price="14", description="Shave your face")) p.menus[1].menu_items.append( MenuItem(name="Color", price="40", description="A lovely color for your hair")) p.menus[1].menu_items.append( MenuItem(name="Blowout", price="150", description="Blast it to the moon")) p.menus[1].menu_items.append( MenuItem(name="Trim", price="25", description="Keep things neat and tidy")) p.menus[1].menu_items.append( MenuItem(name="Cut and Style", price="60", description="The full package")) p.gallery = Gallery() for num in range(1, 40): p.gallery.photos.append( Photo(url="http://placehold.it/600x900&text={}".format(num), sm_thumb="http://placehold.it/450x450&text={}".format(num), lg_thumb="http://placehold.it/550x550&text={}".format(num))) p.save() p.index() # Consumer c = Consumer(user=ud.create_user(email='*****@*****.**', password=password, first_name='Bob', last_name='Johnson')) c.user.confirmed_at = datetime.date.today() c.consumer_url = 'bob.johnson' c.favorites.append(Provider.get(10)) c.favorites.append(Provider.get(15)) c.favorites.append(Provider.get(94)) db.session.add(c) db.session.commit()
def setUp(self): app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" db.create_all() self.client = app.test_client() upload = Photo("Existing Photo", 123456, 0, 'hello.jpg') db.session.add(upload) db.session.commit()
def save_and_resize(photo_form, user_id: str, preserve_metadata: bool): f = photo_form.photo.data new_uuid = uuid.uuid4().hex ext = f.filename.rpartition(".")[-1].lower() new_name = f"{new_uuid}.{ext}" profile_path = app.config["UPLOAD_FOLDER"].joinpath(user_id, "profile") image_path = profile_path.joinpath(new_name) try: f.save(str(image_path)) with Image.open(image_path) as im: if ext in ["jpg", "jpeg"] and im.mode != "RGB": im = im.convert("RGB") exif = {} if preserve_metadata: exif_data = im.info.get("exif") if exif_data: exif = {"exif": exif_data} # icon small = im.resize((24, 24), Image.LANCZOS) small_path = profile_path.joinpath(f"{new_uuid}-small.{ext}") small.save(small_path, optimize=True, quality=85, **exif) # posts image medium = im.resize((40, 40), Image.LANCZOS) medium_path = profile_path.joinpath(f"{new_uuid}-medium.{ext}") medium.save(medium_path, optimize=True, quality=85, **exif) # profile image(overwrites original) im = im.resize((160, 160), Image.LANCZOS) im.save(image_path, optimize=True, quality=85, **exif) existing_photo = Photo.query.filter_by(user_id=int(user_id)).first() if existing_photo: old_uuid = existing_photo.new_name.rpartition(".")[0] existing_photo.unsafe_name = f.filename existing_photo.new_name = new_name db.session.commit() delete_images_starting_with_name_else_log_path(user_id, old_uuid) else: photo = Photo(unsafe_name=f.filename, new_name=new_name, user_id=int(user_id)) db.session.add(photo) db.session.commit() # delete uploaded photo & resized versions, and inform user of problem. except UnidentifiedImageError: photo_logger.error(f"UnidentifiedImageError for user: {user_id}") delete_images_starting_with_name_else_log_path(user_id, new_uuid) photo_form.photo.errors.append( "An image could not be located in that file.") except (Image.DecompressionBombError, Image.DecompressionBombWarning): photo_logger.error(f"DecompressionBombWarning for user: {user_id}") delete_images_starting_with_name_else_log_path(user_id, new_uuid) photo_form.photo.errors.append("Image contains too many pixels. " "Please resize it and try again.") except Exception: photo_logger.exception(f"profile image error for user: {user_id}") delete_images_starting_with_name_else_log_path(user_id, new_uuid) photo_form.photo.errors.append( "An unexpected error occured. Please try again, " "or contact support.")
def addToDB(writeName, attr, user_id): with app.app_context(): # url = url_for('album.uploaded_file', filename=writeName, _external=True) url = 'http://' + app.config['SERVER_NAME'] + '/album/' + writeName user = User.query.get(user_id) photo = Photo(url=url, tn_url=url, filename=writeName) user.album.append(photo) photo.tags.append(Tag(attr=attr)) db.session.commit() return photo.id
def gallery(): template = env.get_template('gallery_add.html') if request.method == 'GET': photos = Photo.select() return template.render(photos=photos) elif request.method == 'POST': photo_file = request.files.get('photo') file_ext = os.path.splitext(photo_file.filename)[1] gallery_folder = static_path('img/gallery/') f_name = generate_filename(prefix='photo', suffix=file_ext) file_path = os.path.join(gallery_folder, f_name) # photo_file.save('/img/gallery/') # new Bottle with open(file_path, 'wb') as open_file: open_file.write(photo_file.file.read()) photo = Photo.create(desc=post_get('desc'), photo=f_name) app.flash('Picture added to the gallery') redirect('/gallery_add')
def test_year_paginator(self): # Set up some mock objects first_photo = Photo() first_photo.created_time = date(2012, 02, 29) db.session.add(first_photo) db.session.commit() self.assertIn(first_photo, db.session) # Year two second_photo = Photo() second_photo.created_time = date(2013, 03, 01) db.session.add(second_photo) db.session.commit() self.assertIn(second_photo, db.session) # Year three third_photo = Photo() third_photo.created_time = date(2014, 03, 01) db.session.add(third_photo) db.session.commit() self.assertIn(third_photo, db.session) # Create pagination after photos pagination = Pagination(2012) self.assertEqual(3, pagination.pages) # Check these before and after iterating through paginator self.assertFalse(pagination.has_prev) self.assertTrue(pagination.has_next) # We should get 3 photos back with the expected date range expected_years = [ (first_photo, date(2012, 02, 29), date(2013, 02, 28)), (second_photo, date(2013, 03, 01), date(2014, 02, 28)), (third_photo, date(2014, 03, 01), date(2015, 02, 28)) ] for expected, actual in izip(expected_years, pagination.iter_pages()): self.assertEqual(expected, actual) self.assertEqual(expected[1].year, pagination.page) self.assertTrue(pagination.has_prev) self.assertFalse(pagination.has_next)
def test_create_photo(self): # Start with photo photo = Photo() photo.instagram_id = '757677846642235453_1134805' photo.caption = '126. Who needs fireworks anyway' photo.created_time = datetime(2012, 02, 29) photo.featured_on = 'Josh Johnson; #JJ' photo.link = 'http://instagram.com/p/qDVDHkyxvS/' db.session.add(photo) db.session.commit() self.assertIn(photo, db.session) # Mock some images hi_img = Image() hi_img.height = 640 hi_img.width = 640 hi_img.url = 'http://scontent-b.cdninstagram.com/hphotos-xpa1/t51.2885-15/10522310_677385995673625_267718762_n.jpg' hi_img.type = 'standard_resolution' low_img = Image() low_img.height = 306 low_img.width = 306 low_img.url = 'http://scontent-b.cdninstagram.com/hphotos-xpa1/t51.2885-15/10522310_677385995673625_267718762_a.jpg' low_img.type = 'low_resolution' thumb_img = Image() thumb_img.height = 150 thumb_img.width = 150 thumb_img.url = 'http://scontent-b.cdninstagram.com/hphotos-xpa1/t51.2885-15/10522310_677385995673625_267718762_s.jpg' thumb_img.type = 'thumbnail' images = [hi_img, low_img, thumb_img] db.session.add_all(images) db.session.commit() self.assertTrue(all(i in db.session for i in images)) # Connect images to photo photo.images.extend(images) db.session.commit() self.assertTrue(all(i in photo.images for i in images)) self.assertTrue(all(photo is i.photo for i in images)) # Mock location and tag loc = Location() loc.instagram_id = '1' loc.name = 'Dogpatch Labs' loc.latitude = 37.782 loc.longitude = -122.387 db.session.add(loc) db.session.commit() self.assertIn(loc, db.session) tag = Tag() tag.name = 'july4th' db.session.add(tag) db.session.commit() self.assertIn(tag, db.session) # Connect location and tag to photo photo.locations.append(loc) photo.tags.append(tag) db.session.commit() self.assertIn(loc, photo.locations) self.assertIn(tag, photo.tags) self.assertIn(photo, loc.photos) self.assertIn(photo, tag.photos)