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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 entrypho(form, photo_id=None, photo=None): if form.validate_on_submit(): if photo_id == None: photo = Photo(name=form.name.data, price=form.price.data) db.session.add(photo) else: form.populate_obj(photo) db.session.commit() else: errors = form.errors
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 setUp(self): app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" db.create_all() upload = Photo("Photo1", 123456, 0, 'photo1.jpg') db.session.add(upload) db.session.commit() photo = Photo.query.get(1) setattr(photo, "file_path", "./uploads/1.png") db.session.add(photo) db.session.commit()
def save_file_url_to_mysql_is_ok(user_id, file_url): if not all([user_id, file_url]): print("参数不足") return False try: photo = Photo(url=file_url, user_id=user_id) db.session.add(photo) db.session.commit() except Exception as e: print(e) return False return True
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 photo_add(): form = PhotoForm() if form.validate_on_submit(): data = form.data photo = Photo( title=data['title'], logo=data['logo'] ) db.session.add(photo) db.session.commit() flash("上传照片成功!", "ok") operate_log("添加照片:%s" % data['title']) return render_template('admin/photo_add.html', form=form)
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 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 add_pokemons(dryrun=True): try: f = open('app/data/pokemon', 'r') for line in f: v = line.split(" ") # 編號、中文、日文、英文 seq = int(v[0][1:]) e = " ".join(v[3:]).strip().lower() c = v[1].strip() if Term.query.filter_by(english=e, chinese=c).first(): pass else: print("%s, %s" % (c, e)) term = Term(english=e, chinese=c, hit_counts=0) if not dryrun: db.session.add(term) term = Term.query.filter_by(english=e, chinese=c).first() if Photo.query.filter_by(term=term).first(): pass else: if seq <= 151: photo = Photo(term=term, url="https://rankedboost.com/wp-content/plugins/ice/riot/poksimages/pokemons/%03d.png" % (seq)) if not dryrun: db.session.add(photo) elif seq <= 251: photo = Photo(term=term, url="https://rankedboost.com/wp-content/plugins/ice/riot/poksimages/pokemons2/%03d.png" % (seq)) if not dryrun: db.session.add(photo) db.session.commit() except Exception as e: print(e) pass
def create_post(): post_type = request.form['post_type'] description = request.form['description'] user_id = int(request.form['user_id']) created_at = request.form['created_at'] post_type_rec = PostType.query.filter(PostType.type==post_type).first() if "location" in request.form: location = request.form['location'] location_rec = Location(location=location) db.session.add(location_rec) db.session.commit() location_id = location_rec.id else: location_id = None post = Post(user_id=user_id, description=description, type_id=post_type_rec.id, created_at=created_at, location_id=location_id ) db.session.add(post) db.session.commit() if "photo" in request.files: photo = request.files['photo'] photo_link = upload_file_to_s3(photo) photo_rec = Photo(path=photo_link, post_id=post.id) db.session.add(photo_rec) if "tagged_friends" in request.form: tagged_friends = request.form['tagged_friends'] friends = tagged_friends.split(',') for friend in friends: print(friend) friend_id = int(friend) tagged_friend = TaggedFriend(user_id=friend_id, post_id=post.id) db.session.add(tagged_friend) db.session.commit() # db.session.add(post) db.session.commit() return "done"
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['ALBUM_UPLOAD_PATH'], filename)) filename_s = resize_image( f, filename, current_app.config['ALBUM_PHOTO_SIZE']['small']) filename_m = resize_image( f, filename, current_app.config['ALBUM_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')