def icons(overwrite, subfolder): """Initialize icons.""" # Update icons icon_path = os.path.join(app.config['IMAGE_ROOT_PATH'], 'resources', subfolder) files = [f for f in os.listdir(icon_path) if f.endswith('.svg')] for file in files: url = os.path.join(icon_path, file) name = os.path.splitext(file)[0] existing_image = Image.query.filter_by(name=name).first() if existing_image: if overwrite: try: existing_image.update(url, keep_original=True, name=name) existing_image.description = 'Static image' if not existing_image.vector: create_thumbnails(existing_image) db.session.commit() except: print('Updating icon {} failed'.format(file)) db.session.rollback() else: try: image = Image(url, keep_original=True, name=name) image.description = 'Static image' if not image.vector: create_thumbnails(image) db.session.add(image) db.session.commit() except: print('Adding icon {} failed'.format(file)) db.session.rollback()
def currency_flags(overwrite): """Initialize currency flags.""" # Update flags flag_path = os.path.join(app.config['IMAGE_ROOT_PATH'], 'resources', 'flags') existing_currencies = Currency.query.all() for currency in existing_currencies: country_code = currency.code[0:2].upper() url = os.path.join(flag_path, country_code + '.svg') if currency.image: if overwrite: try: currency.image.update(url, keep_original=True, name=country_code) currency.image.description = 'Static image' if not currency.image.vector: create_thumbnails(currency.image) db.session.commit() except: print('Adding flag for {} failed'.format(country_code)) db.session.rollback() else: try: image = Image(url, keep_original=True, name=country_code) image.description = 'Static image' if not image.vector: create_thumbnails(image) currency.image = image db.session.commit() except: print('Adding flag for {} failed'.format(country_code)) db.session.rollback()
def upload_file(file): config_upload = current_app.config['UPLOAD'] resp = {'code': 200, 'msg': '操作成功~~', 'data': {}} filename = file.filename ext = filename.rsplit(".", 1)[1] # if ext not in config_upload['ext']: # resp['code'] = -1 # resp['msg'] = "不允许的扩展类型文件" # return resp root_path = current_app.root_path + config_upload['prefix_url'] file_dir = date_to_str(format="%Y%m%d") save_dir = root_path + file_dir if not os.path.exists(save_dir): os.mkdir(save_dir) os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO) file_name = str(uuid.uuid4()).replace("-", "") + "." + ext file.save("{0}/{1}".format(save_dir, file_name)) with db.auto_commit(): model_image = Image() model_image.file_key = file_dir + "/" + file_name db.session.add(model_image) resp['data'] = {'file_key': model_image.file_key} return resp
def new(): """Create a new blog post. **Route:** ``/admin/posts/new`` **Methods:** ``POST`` """ form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.data = str(g.user.id) upload_form = UploadImageForm() if form.validate_on_submit(): author = User.objects().get(id=ObjectId(form.author.data)) post = BlogPost(title=form.title.data, slug=form.slug.data, images=[Image.objects().get(filename=fn) for fn in form.images.data], markdown_content=form.body.data, author=author, posted_by=g.user) post.save() if form.published.data: post.publish() else: post.unpublish() return redirect(url_for('.index')) images = Image.objects() return render_template('admin/posts/edit.html', user=g.user, form=form, images=images, upload_form=upload_form)
def upload(): """Upload an image to Eventum **Route:** ``/admin/media/upload`` **Methods:** ``POST`` """ form = UploadImageForm(request.form) uploaded_from = form.uploaded_from.data if form.validate_on_submit(): f = request.files['image'] if f and allowed_file(f.filename.lower()): filename = create_filename(f, request.form['filename']) f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) image = Image(filename=filename, default_path=app.config['RELATIVE_UPLOAD_FOLDER']+filename, creator=g.user) image.save() return redirect(url_for('.index')) flash("Filename {} is invalid".format(f.filename)) if form.errors: flash(form.errors) if uploaded_from: return redirect(uploaded_from) return render_template('admin/media/upload.html', form=form)
def import_image(guid, path, add_to_class, add_to_id): try: # Saving the image to a new file user = User.get_by_guid_or_404(guid) image = Image(path) image.description = 'Image uploaded by {}'.format(user.username) db.session.add(image) if add_to_class == 'User': add_to_user = User.query.get(add_to_id) add_to_user.profile_picture = image elif add_to_class == 'Event': add_to_event = Event.query.get(add_to_id) add_to_event.image = image elif add_to_class == 'EventUser': add_to_eventuser = EventUser.query.get(add_to_id) add_to_eventuser.profile_picture = image elif add_to_class == 'Expense': add_to_expense = Expense.query.get(add_to_id) add_to_expense.image = image elif add_to_class == 'Settlement': add_to_settlement = Settlement.query.get(add_to_id) add_to_settlement.image = image db.session.commit() # Create thumbnails create_thumbnails(image, update_progress=True) except: _set_task_progress(100) app.logger.error('Unhandled exception', exc_info=sys.exc_info())
def upload_categ_BG(id): if (current_user.role_id != 2): return json.dumps({'success': False}) categ = Categ.query.get_or_404(id) if 'file' not in request.files: return json.dumps({'success1': False}) file = request.files['file'] img = Image(hex_id=id) img.ext = file.mimetype.replace('image/', '') if (not img.ext in ['png', 'jpg', 'jpeg', 'gif']): return json.dumps({'success2': False}) db.session.add(img) db.session.commit() try: file.save(os.getcwd() + f"/app/static/uploadedImgs/{img.id}.{img.ext}") except BaseException: db.session.delete(img) db.session.commit() return json.dumps({'success3': False}) categ.BG_img = f'{img.id}.{img.ext}' db.session.add(categ) db.session.commit() return json.dumps({'success': True})
def import_from_directory(path_to_images): connect("eventum") creator = User.objects().get(gplus_id="super") filenames = os.listdir(path_to_images) filenames = [fn for fn in filenames if not fn.startswith(".")] failures = [] for filename in filenames: if Image.objects(filename=filename).count() > 0: img = Image.objects().get(filename=filename) img.delete() old_path = os.path.join(path_to_images, filename) shutil.copy(old_path, config["UPLOAD_FOLDER"]) default_path = config["RELATIVE_UPLOAD_FOLDER"] + filename image = Image(filename=filename, default_path=default_path, creator=creator) try: image.save() except ValidationError as e: failures.append(filename) print "FAIL: %s" % filename print e print "Processed %s images." % len(filenames) print "%s success." % (len(filenames) - len(failures)) print "%s failures." % len(failures)
def handle_request(): if request.method == 'POST': if request.files: username = '******' filename = images.save(request.files['image']) url = images.url(filename) #--------------------- result = predict(filename) #--------------------- user = User.query.filter_by(username=username).first() if user is None: user = User(username=username) report = Report(user=user, data=json.dumps(result)) image = Image(report=report) image.image_filename = filename image.image_url = url db.session.add(user) db.session.add(report) db.session.add(image) db.session.commit() return 'Report Generated' return 'No Files Recieved' return 'Method not POST'
def store_image(request): # get image from request img_b64 = json.loads(request.data)["image"] # decode base64 img_bytes = base64.b64decode(img_b64) # encode to uint8 to create a numpy array img_np_array = np.fromstring(img_bytes, np.uint8) # decode image img = cv2.imdecode(img_np_array, cv2.IMREAD_COLOR) # we add the image to the db to obtain the id, so every filename is different image = Image(img="") db.session.add(image) db.session.commit() # save image to a file filename = app.config[ "STUDENT_PHOTOS_FOLDER_PATH"] + "unknown-face-{0:0>3}.jpg".format( image.id) cv2.imwrite(filename, img) # update filename of the image image.img = filename db.session.commit() return image
def seed_images(): demo = Image( postId=1, imgUrl="http://fantsy-app.s3.amazonaws.com/EzgdmaCQuT84bgDL4fhXZS.jpg") db.session.add(demo) demo2 = Image( postId=2, imgUrl= "http://fantsy-app.s3.amazonaws.com/31531798_10211165893878446_1339226057647063040_n.jpg" ) db.session.add(demo2) demo3 = Image( postId=3, imgUrl="http://fantsy-app.s3.amazonaws.com/0bvu6xbvqk331.jpg") db.session.add(demo3) demo4 = Image( postId=4, imgUrl= "http://fantsy-app.s3.amazonaws.com/13906815_10206659420339424_2444900124464175857_n.jpg" ) db.session.add(demo4) demo5 = Image(postId=5, imgUrl="http://fantsy-app.s3.amazonaws.com/unnamed.jpg") db.session.add(demo5) db.session.commit() db.session.commit()
def post(self, request, *args, **kwargs): if len(Item.objects.filter(user=request.user)) > 500: return redirect('home') form = self.form_class(request.POST) if form.is_valid(): item_data = { k: v for k, v in form.cleaned_data.items() if 'image' not in k } item_data['user'] = request.user categories = item_data.pop('categories') item = Item(**item_data) item.save() item.categories = categories item.save() images_data = { k: v for k, v in form.cleaned_data.items() if 'image' in k } for key in sorted(k for k, v in images_data.items() if v): url = images_data[key] image = Image(item=item, url=url) image.save() send_emails(request, item) response = redirect('view_item', item.id) response['Location'] += '?new=true' return response else: return render(request, 'app/add_item.html', {'form': form})
def new(): """Create a new blog post. **Route:** ``/admin/posts/new`` **Methods:** ``POST`` """ form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.data = str(g.user.id) upload_form = UploadImageForm() if form.validate_on_submit(): author = User.objects().get(id=ObjectId(form.author.data)) post = BlogPost(title=form.title.data, slug=form.slug.data, images=[Image.objects().get(filename=fn) for fn in form.images.data], markdown_content=form.body.data, author=author, posted_by=g.user, tags=form.tags.data) post.save() if form.published.data: post.publish() else: post.unpublish() return redirect(url_for('.index')) images = Image.objects() return render_template('admin/posts/edit.html', user=g.user, form=form, images=images, upload_form=upload_form)
def seed_images(): demo = Image(postId=1, imgUrl="http://fantsy-app.s3.amazonaws.com/EzgdmaCQuT84bgDL4fhXZS.jpg") db.session.add(demo) demo2 = Image(postId=2, imgUrl="http://fantsy-app.s3.amazonaws.com/31531798_10211165893878446_1339226057647063040_n.jpg") db.session.add(demo2) demo3 = Image(postId=3, imgUrl="http://fantsy-app.s3.amazonaws.com/0bvu6xbvqk331.jpg") db.session.add(demo3) demo4 = Image(postId=4, imgUrl="http://fantsy-app.s3.amazonaws.com/13906815_10206659420339424_2444900124464175857_n.jpg") db.session.add(demo4) demo5 = Image(postId=5, imgUrl="http://fantsy-app.s3.amazonaws.com/unnamed.jpg") db.session.add(demo5) db.session.commit() # for i in range(30): # postId = random.randint(1, 30) # imgUrl = fake.image_url() # fakeImages = Image(postId=postId, imgUrl=imgUrl) # db.session.add(fakeImages) db.session.commit()
def test_data_add(self): admin = User(username='******') admin.set_password('admin') user = User(username='******') user.set_password('user') db.session.add_all([admin, user]) db.session.commit() gcs = storage.Client.from_service_account_json( os.path.join(basedir, GOOGLE_AUTH)) bucket = gcs.bucket(BUCKET_NAME) now = str(int(time.time())) filename_01 = 'photo-1555874952-65f9f7004a62.jpeg' n_filename_01 = now + '_' + filename_01 filename_02 = 'photo-1555874952-2129e5cba057.jpeg' n_filename_02 = now + '_' + filename_02 bolb_01 = bucket.blob(n_filename_01) bolb_01.upload_from_filename( os.path.join(basedir, 'app/static/img/', filename_01)) bolb_01.make_public() bolb_02 = bucket.blob(n_filename_02) bolb_02.upload_from_filename( os.path.join(basedir, 'app/static/img/', filename_02)) bolb_02.make_public() img_01 = Image(title='imgtest1', src=n_filename_01, description='Image Test 01', user_id=user.id, created_at=datetime.datetime.now()) img_02 = Image(title='imgtest2', src=n_filename_02, description='Image Test 02', user_id=admin.id, created_at=datetime.datetime.now()) db.session.add_all([img_01, img_02]) db.session.commit() comment_01 = Comment( content='Comment Test 01 on Image Test 01 comment by user', user_id=user.id, image_id=img_01.id, created_at=datetime.datetime.now()) comment_02 = Comment( content='Comment Test 02 on Image Test 01 comment by admin', user_id=admin.id, image_id=img_01.id, created_at=datetime.datetime.now()) comment_03 = Comment( content='Comment Test 03 on Image Test 02 comment by user', user_id=user.id, image_id=img_01.id, created_at=datetime.datetime.now()) db.session.add_all([comment_01, comment_02, comment_03]) db.session.commit()
def upload_hex_img(id): hex = Hexagon.query.get(id) if hex.user_id != current_user.id: return json.dumps({'success': False}) if 'file' not in request.files: return json.dumps({'success': False}) file = request.files['file'] img = Image(hex_id=id) img.ext = file.mimetype.replace('image/', '') if (not img.ext in ['png', 'jpg', 'jpeg', 'gif' ]): # TODO: создать таблицу с расширениями файлов return json.dumps({'success': False}) db.session.add(img) db.session.commit() categ_name = hex.categ.name create_dir("/app/static/uploadedImgs/" + categ_name) create_dir(f"/app/static/uploadedImgs/{categ_name}/{hex.chain.id}") create_dir( f"/app/static/uploadedImgs/{categ_name}/{hex.chain.id}/{hex.id}") filename = f"static/uploadedImgs/{categ_name}/{hex.chain.id}/{hex.id}/{img.id}.{img.ext}" if 'BG' in file.filename: hex.BG_img = filename for img in hex.imgs: img.is_BG = False db.session.add(img) img.is_BG = True db.session.add_all([hex, img]) db.session.commit() try: file.save(os.getcwd() + "/app/" + filename) except BaseException: db.session.delete(img) db.session.commit() return json.dumps({'success': False}) subs = current_user.subscriptions_to_me for sub in subs: create_notification( sub.subscriber_id, _('User %(username)s changed his/her hexagon in category %(categname)s', categname=hex.categ.name, username=current_user.username), 'change', url_for('get_hex', id=hex.id)) return json.dumps({ 'success': True, 'url': filename, 'uuid': img.id, "isBG": img.is_BG })
def take_frame(self): now = datetime.now() fileName = filePath + now.strftime('%y%m%d_%H%M%S') + '.png' print (fileName) cv2.imwrite(fileName, self.frame) db = Image(image_name=now.strftime('%y%m%d_%H%M%S'), pub_date=timezone.now()) db.save()
def save(self): super(ImageFile, self).save() img = Image() img.file_id = self.id img.image = self.base + '.' + self.ext img.save() return self.base
def delete(filename): if Image.objects(filename=filename).count() == 1: image = Image.objects().get(filename=filename) image.delete() else: flash('Invalid filename') pass return redirect(url_for('.index'))
def init_image(self): self.image = Image( Name='foobar', URL='baz', Sol=42, CameraID=1, ProductTypeID=1, DetatchedLabel=False, )
def test_create_image(self): image = Image() image.height = 640 image.width = 640 image.url = 'http://scontent-b.cdninstagram.com/hphotos-xpa1/t51.2885-15/10522310_677385995673625_267718762_n.jpg' image.type = 'standard_resolution' db.session.add(image) db.session.commit() self.assertIn(image, db.session)
def edit(post_id): try: object_id = ObjectId(post_id) except InvalidId: return abort(404) try: post = BlogPost.objects().with_id(object_id) except (DoesNotExist, ValidationError): flash('Cannot find blog post with id %s.' % post_id) return redirect(url_for('.index')) if request.method == 'POST': form = CreateBlogPostForm(request.form) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.default = str(g.user.id) if form.validate_on_submit(): was_published = post.published should_be_published = form.published.data post.title = form.title.data post.author = User.objects.get(id=ObjectId(form.author.data)) post.slug = form.slug.data post.markdown_content = form.body.data post.images = [Image.objects().get(filename=fn) for fn in form.images.data] if form.featured_image.data: post.featured_image = Image.objects().get(filename=form.featured_image.data) else: post.featured_image = None post.save() if was_published != should_be_published: if was_published: set_published_status(post.id, False) else: set_published_status(post.id, True) return redirect(url_for('.index')) upload_form = UploadImageForm() featured_image = post.featured_image.filename if post.featured_image else None form = CreateBlogPostForm(request.form, title=post.title, slug=post.slug, published=post.published, body=post.markdown_content, images=[image.filename for image in post.images], author=str(post.author.id), featured_image=featured_image) form.author.choices = [ (str(u.id), u.name + " (You)" if u == g.user else u.name) for u in User.objects()] form.author.default = str(g.user.id) images = [image for image in Image.objects() if image not in post.images] return render_template('admin/posts/edit.html', user=g.user, form=form, post=post, images=images, upload_form=upload_form)
def delete(filename): """View all of the uploaded images. **Route:** ``/admin/media/delete/<filename>`` **Methods:** ``POST`` """ if Image.objects(filename=filename).count() == 1: image = Image.objects().get(filename=filename) image.delete() else: flash('Invalid filename', ERROR_FLASH) return redirect(url_for('.index'))
def post_image(): data = request.get_json() or {} if 'image_url' not in data or 'image_filename' not in data: return bad_request('image json needs to be in data ') image = Image() image.from_dict(data) db.session.add(image) db.session.commit() response = jsonify(image.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('get_image', filename=image.image_filename) return response
def create_images(num_images, superuser, printer): """Creates ``num_images`` image objects in the database. It will download sample images from http://lorempixel.com, and add database entries. :param int num_images: The number of images to create :param superuser: The superuser object to associate with the images. :type superuser: :class:`~app.models.User` :param printer: The object to manage progress printing. :type printer: :class:`~script.cli.ProgressPrinter` :returns: A list of images that now exist. :rtype: list(:class:`~app.models.Image`) """ print "Generating images..." printer.line() successes = [] failures = [] skips = [] for width in range(400, 1600, (1600 - 400) / num_images): height = width / 2 filename = BASE_FILENAME.format(width, height) path = config['UPLOAD_FOLDER'] + filename url = BASE_URL.format(width, height) printer.begin_status_line(filename) # Download image if it doesn't exist already if not exists(path): try: urllib.urlretrieve(url, path) except IOError: failures.append((filename, '')) printer.status_fail() continue # Failed to download, move on to the next image. # Insert or fetch image from database if Image.objects(filename=filename).count() == 0: image = Image(filename=filename, default_path=path, creator=superuser) image.save() successes.append((filename, path)) printer.status_success() else: skips.append((filename, path)) printer.status_skip() printer.line() printer.results(len(successes), len(skips), len(failures)) return successes + skips
def upload_img(): upload_path = os.path.join(Config.FS_ROOT_DIR, Config.FS_ROOT_UPLOAD, Config.FS_ROOT_IMG_UPLOAD) abs_up_path = os.path.abspath(upload_path) if not os.path.exists(abs_up_path): os.makedirs(abs_up_path) resp_dict = {'errno': 0, 'data': []} try: files = request.files.to_dict() for filename, file in files.items(): uuid_filename = '{}.{}'.format( shortuuid.uuid(), secure_filename(filename).rsplit('.')[-1]) # compress the upload img compress2png(file, dst=os.path.join(abs_up_path, uuid_filename)) resp_dict['data'].append('/article/img/%s' % uuid_filename.split('.')[0]) img = Image(id=uuid_filename.split('.')[0], local_path=os.path.join(abs_up_path, uuid_filename)) db.session.add(img) db.session.commit() except Exception as e: print(e) resp_dict['errno'] = 1 return jsonify(resp_dict)
def _image(self): """Gets an image to associate with the event, from the database. :returns: The image. :rtype: :class:'~app.models.Image' """ return random.choice(Image.objects())
def upload_image(): if "image" not in request.files: return {"errors": "image required"}, 400 image = request.files["image"] 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 filename 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"] # we can use the new_image = Image(user=current_user, url=url) db.session.add(new_image) db.session.commit() return {"url": url}
def edit(event_id): """""" try: event = Event.objects().get(id=event_id) except (DoesNotExist, ValidationError): flash('Cannont find event with id "%s"' % event_id) return redirect(url_for('.index')) form = EditEventForm(request.form) if request.method == 'POST' else \ EventsHelper.create_form(event, request) if form.validate_on_submit(): try: EventsHelper.update_event(event, form) except GoogleCalendarAPIError as e: flash(e.message) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message) delete_form = DeleteEventForm() upload_form = UploadImageForm() images = Image.objects() return render_template('admin/events/edit.html', form=form, event=event, delete_form=delete_form, upload_form=upload_form, images=images)
def scrap_img(product): """Get all item pictures from VidaXL Args: Product (class) Returns: [JSON]: vidaxl_id, images quantity, list of images urls """ images = Product.query.get(product.id).images if images: return [image.url for image in images] timeout = current_app.config["SLEEP_TIME"] attempts = int(current_app.config["NUMBER_OF_REPETITIONS"]) for i in range(attempts): soup = check_soup(product.vidaxl_id) if soup: gallery = soup.find("div", class_="media-gallery") img_container = gallery.findAll("a") images = [ i.attrs["href"] for i in img_container if "missing_image" not in i ] for img in images: Image(product_id=product.id, url=img).save() return images log( log.INFO, "Scraping pictures: Invalid Response. Attempt: %d(%d) timeout:%s", i + 2, attempts, timeout, ) time.sleep(timeout) timeout += timeout/2 return None
def new_listing(): form = ListingForm() if form.validate_on_submit(): _listing = Listing(title=form.title.data, body=form.body.data, condition=form.condition.data, price=form.price.data, author=current_user) db.session.add(_listing) db.session.commit() # Image upload filename = secure_filename(form.image.data.filename) [filename, ext] = filename.split('.') # ['image', 'png'] instance = 0 db_image = Image.query.filter_by(name=filename).order_by( Image.instance.desc()).first() if db_image and db_image.instance is not None: instance = int(db_image.instance) + 1 location = filename + str(instance) + '.' + ext form.image.data.save( os.path.join(app.config['IMAGES_FOLDER'], location)) image = Image(name=filename, extension=ext, instance=instance, src=location, listing_id=_listing.id) db.session.add(image) db.session.commit() flash('Listing created') return redirect(url_for('listing', id=_listing.id)) return render_template("new_listing.html", title='Create New Listing', form=form)
def remove_images(app): from datetime import datetime while True: time.sleep(1800) conf = app.config['IMAGE_DELETE'] with app.app_context(): if ( datetime.utcnow().hour in conf['TIME_OF_DAY'] and datetime.utcnow().weekday() in conf['WEEKDAY'] ): images = Img.get_all_imgs() db_imgs = [img.location + img.filename for img in images] posts = Post.get_all() post_imgs = get_all_imgs((post.body_html for post in posts)) diff_imgs = set(db_imgs) - set(post_imgs) if diff_imgs: app.logger.debug('Images to delete: {}'.format(db_imgs)) for i in images: if i.location + i.filename in diff_imgs: if os.path.isfile(imgs.path(i.filename)): os.remove(imgs.path(i.filename)) f, e = os.path.splitext(i.filename) if os.path.isfile(imgs.path(f + '_crop' + e)): os.remove(imgs.path(f + '_crop' + e)) db.session.delete(i) db.session.commit()
def post(self): # not sure about it # it could be posted as list incoming_file = request.files['file'] internal_fname = str(uuid.uuid4()) fname= secure_filename(incoming_file.filename) if fname == "": fname = "name_couldnt_detected" file_ext = os.path.splitext(fname)[1] if file_ext not in current_app.config['UPLOAD_EXTENSIONS'] or \ file_ext != validate_image(incoming_file.stream): abort(400) # user maybe needs to be queried user = g.current_user image = Image(internal_fname=internal_fname, owner=user, fname=fname) try: db.session.add(image) db.session.commit() except IntegrityError: return jsonify(message="User with that email already exist"), 409 filepath = os.path.join(basedir, current_app.config["UPLOAD_PATH"] + fname) incoming_file.save(filepath)
def get_random_event_image(self, event): """Return a random event image from the default images directory. """ images_directory = os.path.dirname( __file__) + "/static/images/default_event_images" default_event_images = os.listdir(images_directory) # the while loop is to account for any hidden files in the directory filename = "" while not filename: filename = random.choice(default_event_images) if not filename.startswith("default_event_image"): filename = "" filepath = images_directory + "/" + filename image = Image.query.filter_by(path=filepath).first() if image is None: image = Image( path=filepath, event=event, image_type=ImageType.query.filter_by( name="Main Event Image").first(), ) db.session.add(image) db.session.commit() return image
def create(): """Create a new event. **Route:** ``/admin/events/create`` **Methods:** ``GET, POST`` """ form = CreateEventForm(request.form) if form.validate_on_submit(): try: EventsHelper.create_event(form, g.user) except EventumError.GCalAPI as e: flash(e.message, ERROR_FLASH) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message, ERROR_FLASH) upload_form = UploadImageForm() delete_form = DeleteEventForm() images = Image.objects() return render_template('admin/events/create.html', form=form, delete_form=delete_form, upload_form=upload_form, images=images)
def get_bitmap_by_id(imageid): # select image with matching id and return 404 if no such image found image = Image.select().where(Image.id == imageid) if image.count() == 0: return json.dumps({'message': 'No image with matching ID found!'}), 404 # forward request to image source using proxy return proxy.stream(request, 'GET', BASE_URL_DATASET + image[0].src)
def view(): """Displays all uploaded images. **Route:** ``/admin/media/view`` **Methods:** ``GET`` """ images = Image.objects() return render_template('admin/media/view.html', images=images)
def _images(self): """Gets a list of images from the database if any exist. :returns: The images. :rtype: list(:class:`~app.models.Image`) """ # Fetch self.images if it hasn't been fetched if self.images is None: self.images = list(Image.objects().limit(5)) return self.images
def index(): """View all of the uploaded images. **Route:** ``/admin/media`` **Methods:** ``GET`` """ images = Image.objects() form = UploadImageForm() return render_template('admin/media/media.html', images=images, form=form)
def image_with_same_name(form, field): """A validator that ensures that there is an image in the database with the filename that is the same as the field's data. :param form: The parent form :type form: :class:`Form` :param field: The field to validate :type field: :class:`Field` """ if Image.objects(filename=field.data).count() != 1: return ValidationError( message="Can't find image '{}' in the database".format(field.data))
def upload(): """Upload an image to Eventum :returns: A JSON containing the status of the file upload, or error messages, if any. :rtype: json """ form = UploadImageForm(request.form) if form.validate_on_submit(): f = request.files['image'] if f: filename = create_filename(f, request.form['filename']) f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) default_path = app.config['RELATIVE_UPLOAD_FOLDER'] + filename image = Image(filename=filename, default_path=default_path, creator=g.user) image.save() return jsonify({"status": "true"}) if form.errors: return jsonify(form.errors) return jsonify({"status": "error"})
def run(self): """Run the generation. Uses the configurations passed to func:`__init__`. """ # Setup: db connection, superuser, and printer. connect(config['MONGODB_SETTINGS']['DB']) try: superuser = User.objects().get(gplus_id='super') except DoesNotExist: print ('Failed to get superuser. Try running:\n' '\texport GOOGLE_AUTH_ENABLED=TRUE') printer = ProgressPrinter(self.quiet) # Images if self.should_gen_images: if self.wipe: self.warn('Image') print CLIColor.warning('Wiping Image database.') Image.drop_collection() create_images(12, superuser, printer) # Blog posts if self.should_gen_posts: if self.wipe: self.warn('BlogPost') print CLIColor.warning('Wiping BlogPost database.') BlogPost.drop_collection() create_posts(10, superuser, printer) # Events and event series if self.should_gen_events: if self.wipe: self.warn('Event and EventSeries') print CLIColor.warning('Wiping Event database.') Event.drop_collection() print CLIColor.warning('Wiping EventSeries database.') EventSeries.drop_collection() create_events(superuser, printer)
def page_image(title_id, page_num): """Get archive file corresponding to title ID and member file corresponding to page number Returns extracted image to browser""" # Get title information try: volume = Volume.get(Volume.id == title_id) except Volume.DoesNotExist: abort(404) # Get page information try: page = Image.select().join(Volume).where((Volume.id == title_id) & (Image.page == page_num)).get() except Image.DoesNotExist: abort(404) if volume.filetype == 'zip': # TODO: Error check on archive open z = zipfile.ZipFile(INPUT_PATH+volume.filename) # Get page binary data # TODO: Error checking zf = z.read(page.filename) z.close() # Return extracted image to browser return send_file(BytesIO(zf), mimetype=page.mimetype) elif volume.filetype == 'rar': # TODO: Error check on archive open rar = rarfile.RarFile(INPUT_PATH+volume.filename) # Get page binary data # TODO: Error checking rardata = rar.read(page.filename) rar.close() # Return extracted image to browser return send_file(BytesIO(rardata), mimetype=page.mimetype) # unrecognised archive type else: abort(500)
def index(): """View and manage users Whitelisted users are the only ones allowed to make user accounts. """ upload_form = UploadImageForm() whitelist_form = AddToWhitelistForm() return render_template('admin/users/users.html', whitelist_form=whitelist_form, upload_form=upload_form, whitelist=Whitelist.objects(redeemed=False), users=User.objects(), images=Image.objects(), current_user=g.user)
def __call__(self, form, field): """Called internally by :mod:`wtforms` on validation of the field. :param form: The parent form :type form: :class:`Form` :param field: The field to validate :type field: :class:`Field` :raises: :class:`wtforms.validators.ValidationError` """ filename = '{}.'.format(field.data) if Image.objects(filename__startswith=filename).count(): raise ValidationError(self.message)
def event_data_from_form(cls, form, creator=None): """Translate a :class:`~app.forms.CreateEventForm` or a subclass into a dictionary of event data. :param form: The form to translate. :type form: :class:`~app.forms.CreateEventForm` or a subclasss :param creator: The creator of the event. :type creator: :class:`~app.models.User` :returns: Event data. :rtype: dict """ if not form: return {} event_image = None filename = form.event_image.data if filename and Image.objects(filename=filename).count() == 1: event_image = Image.objects().get(filename=filename) event_data = { 'title': form.title.data, 'slug': form.slug.data, 'location': form.location.data, 'start_time': form.start_time.data, 'end_time': form.end_time.data, 'published': form.published.data, 'short_description_markdown': form.short_description.data, 'long_description_markdown': form.long_description.data, 'is_recurring': form.is_recurring.data, 'facebook_url': form.facebook_url.data, 'image': event_image } if creator: event_data['creator'] = creator return event_data
def slide(title_id): """Test template for Unslider display, displays Title title_id""" # Get title information try: volume = Volume.get(Volume.id == title_id) except Volume.DoesNotExist: abort(404) # Get list of images for this title pages = Image.select(Image, Volume).join(Volume).where( Volume.id == title_id).order_by(Image.page) # Pass volume and page details to Unslider template return render_template("slider.html", title_id=title_id, volume=volume, pages=pages)
def event_data_from_form(klass, form, creator=None): if not form: return {} event_image = None filename = form.event_image.data if filename and Image.objects(filename=filename).count() == 1: event_image = Image.objects().get(filename=filename) event_data = { 'title': form.title.data, 'slug': form.slug.data, 'location': form.location.data, 'start_time': form.start_time.data, 'end_time': form.end_time.data, 'published': form.published.data, 'short_description_markdown': form.short_description.data, 'long_description_markdown': form.long_description.data, 'is_recurring': form.is_recurring.data, 'facebook_url': form.facebook_url.data, 'image': event_image } if creator: event_data['creator'] = creator return event_data
def create(): """""" form = CreateEventForm(request.form) if form.validate_on_submit(): try: EventsHelper.create_event(form, g.user) except GoogleCalendarAPIError as e: flash(e.message) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message) upload_form = UploadImageForm() delete_form = DeleteEventForm() images = Image.objects() return render_template('admin/events/create.html', form=form, delete_form=delete_form, upload_form=upload_form, images=images)
def index(): """View and manage users. Whitelisted users are the only ones allowed to make user accounts. **Route:** ``/admin/users`` **Methods:** ``GET`` """ upload_form = UploadImageForm() whitelist_form = AddToWhitelistForm() return render_template( "admin/users/users.html", whitelist_form=whitelist_form, upload_form=upload_form, whitelist=Whitelist.objects(redeemed=False), users=User.objects(), images=Image.objects(), current_user=g.user, )
def title(title_id): """ Render title (grid of thumbnails). Image 0 as blurred CSS background? """ # Get title information try: volume = Volume.get(Volume.id == title_id) except Volume.DoesNotExist: abort(404) # Get list of images for this title thumbs = Image.select(Image, Volume).join(Volume).where(Volume.id == title_id).order_by(Image.page) # Get list of tags for this title tags = Tag.select(Tag, TagRelation, Volume).join(TagRelation).join(Volume).where(Volume.id == title_id).order_by(Tag.name) # pass list of thumbnails to template return render_template("title.html", title=volume.title, id=str(title_id), thumbs=thumbs, tags=tags)
def register_delete_rules(): """Registers rules for how Mongoengine handles the deletion of objects that are being referenced by other objects. See the documentation for :func:`mongoengine.model.register_delete_rule` for more information. All delete rules for User fields must by DENY, because User objects should never be deleted. Lists of reference fields should PULL, to remove deleted objects from the list, and all others should NULLIFY """ from app.models import Event, EventSeries, User, Post, BlogPost, Image from mongoengine import NULLIFY, PULL, DENY Event.register_delete_rule(EventSeries, 'events', PULL) Image.register_delete_rule(BlogPost, 'images', PULL) Image.register_delete_rule(User, 'image', NULLIFY) Image.register_delete_rule(BlogPost, 'featured_image', NULLIFY) Image.register_delete_rule(Event, 'image', NULLIFY) EventSeries.register_delete_rule(Event, 'parent_series', NULLIFY) User.register_delete_rule(Event, 'creator', DENY) User.register_delete_rule(Image, 'creator', DENY) User.register_delete_rule(Post, 'author', DENY) User.register_delete_rule(Post, 'posted_by', DENY)
def edit(event_id): """Edit an existing event. **Route:** ``/admin/events/edit/<event_id>`` **Methods:** ``GET, POST`` :param str event_id: The ID of the event to edit. """ try: event = Event.objects().get(id=event_id) except (DoesNotExist, ValidationError): flash('Cannot find event with id "{}"'.format(event_id), ERROR_FLASH) return redirect(url_for('.index')) form = EditEventForm(event, request.form) if request.method == 'POST' else \ EventsHelper.create_form(event, request) if form.validate_on_submit(): try: EventsHelper.update_event(event, form) except EventumError.GCalAPI as e: flash(e.message, ERROR_FLASH) return redirect(url_for('.index')) if form.errors: for error in form.errors: for message in form.errors[error]: flash(message, ERROR_FLASH) delete_form = DeleteEventForm() upload_form = UploadImageForm() images = Image.objects() return render_template('admin/events/edit.html', form=form, event=event, delete_form=delete_form, upload_form=upload_form, images=images)