def run(self):
        self.saveImage()

        return {
            "original_image":
            photos.url(self.DEFAULT_IMAGE),
            "compress_image":
            photos.url(self.setterPath().get('path')),
            "original_image_size":
            round(os.stat(self.IMAGE).st_size / 1024, 2),
            "compress_image_size":
            round(
                os.stat(self.setterPath().get('full_path')).st_size / 1024, 2)
        }
    def run(self):
        self.BACKGROUND.save(self.setterPath().get('full_path'),
                             optimize=True,
                             quality=0)

        return {
            "original_image":
            photos.url(self.DEFAULT_IMAGE),
            "compress_image":
            photos.url(self.setterPath().get('path')),
            "original_image_size":
            round(os.stat(self.IMAGE).st_size / 1024, 2),
            "compress_image_size":
            round(
                os.stat(self.setterPath().get('full_path')).st_size / 1024, 2)
        }
Пример #3
0
    def get_avatar(self):
        if self.avatar is not None:
            return photos.url(self.avatar.path)

        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            digest, 128)
Пример #4
0
def edit_by_id(id):
    user = session['user']
    logged_in = True
    the_user = models.User.query.filter_by(username=user).first()
    the_settings = models.Settings.query.filter_by(user=the_user.id).first()
    display_name = the_settings.displayName

    post = models.Content.query.filter_by(id=id).first()

    if request.method == 'POST' and 'photo' in request.files:
        form = request.form
        pic = request.files['photo']
        filename = photos.save(pic)
        user = session['user']
        url = photos.url(filename)
        rec = models.Photo(filename=filename, user=user, url=url)
        db.session.add(rec)
        db.session.commit()
        if form is not None:
            res = posts.update_post_in_db(id, form["content"], url)
            print res
        else:
            print "nothing to update in db"
        return redirect(url_for('read'))

    return render_template('editPost.html',
                           post=post,
                           user=user,
                           logged_in=logged_in,
                           displayName=display_name)
Пример #5
0
def add_category():
    """
	add a category to the
	database
	"""
    check_admin()

    add_category = True

    form = CategoriesForm()

    if form.validate_on_submit():
        filename = request.files['image']
        _, f_ext = os.path.splitext(filename.filename)
        name = form.name.data
        picture_fn = name + f_ext
        photos.save(filename, name=picture_fn)
        url = photos.url(picture_fn)
        category = Categories(category_name=form.name.data, category_image=url)
        try:
            db.session.add(category)
            db.session.commit()
            flash("You have successfully added a new category")
            gc.collect()
        except Exception as e:
            flash('Error: category name already exits. ')

        return redirect(url_for('admin.list_categories'))
    return render_template('admin/categories/category.html',
                           action="Add",
                           form=form,
                           add_category=add_category,
                           title="Add Categories")
Пример #6
0
def edit_by_id(id):
    user = session['user']
    logged_in = True
    the_user = models.User.query.filter_by(username=user).first()
    the_settings = models.Settings.query.filter_by(user=the_user.id).first()
    display_name = the_settings.displayName

    post = models.Content.query.filter_by(id=id).first()

    if request.method == 'POST' and 'photo' in request.files:
        form = request.form
        pic = request.files['photo']
        filename = photos.save(pic)
        user = session['user']
        url = photos.url(filename)
        rec = models.Photo(filename=filename, user=user, url=url)
        db.session.add(rec)
        db.session.commit()
        if form is not None:
            res = posts.update_post_in_db(id, form["content"], url)
            print res
        else:
            print "nothing to update in db"
        return redirect(url_for('read'))

    return render_template('editPost.html', post=post, user=user, logged_in=logged_in, displayName=display_name)
Пример #7
0
    def post(self):

        parser = reqparse.RequestParser()
        parser.add_argument("Image", type=FileStorage, location="files", required=True, nullable=False,
                            help="Image参数类型不正确或缺失")
        args = parser.parse_args()
        filename = args.get("Image").filename

        # 去掉文件后缀末尾双引号
        ext = filename.rsplit('.', 1)[1].replace("\"", "").replace("\"", "")

        # 对图片保存名称唯一
        key = filename + current_app.config["SECRET_KEY"]
        md5 = hashlib.md5()
        md5.update(key.encode('utf-8'))
        filename = md5.hexdigest()

        try:
            file_name = photos.save(args.get("Image"), folder=None, name=filename + '.' + ext)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.THIRDERR, message="上传图片失败,只支持jpg,png类型")

        # 获得保存后的图片路径
        try:
            image_url = photos.url(file_name)
            base_name = photos.get_basename(file_name).rsplit('.', 1)[0]

            c_url = create_thumbnail(base_name, ext)
        except Exception as e:
            current_app.logger.error(e)

        return jsonify(code=RET.OK, message="图片上传成功", image_url=image_url, c_url=c_url)
def index():
    form = PostForm()
    if form.validate_on_submit():
        for filename in request.files.getlist('photo'):
            str_name = 'admin' + str(int(time.time()))
            name = hashlib.md5(str_name.encode("utf-8")).hexdigest()[:15]
            photos.save(filename, name=name + '.')
            post = Post(title=form.post.data,
                        url=photos.url(name) + '.jpg',
                        author=current_user,
                        filename=name + '.jpg')
            db.session.add(post)
            db.session.commit()
            flash('Your post is now live!')
            return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template("index.html",
                           title='Home Page',
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
Пример #9
0
def Upload(file):
    # filename = hashlib.md5(current_user.username + str(time.time())).hexdigest()[:10]
    # filename.update(hash.encode("utf-8"))
    # photo = photos.save(file, name=filename + '.')
    photo = photos.save(file)
    if photo:
        url = photos.url(photo)
    return url
Пример #10
0
def update():
    if current_user.role == 'admin':
        if request.method == 'POST':
            product_form_dict = dict(request.form)
            product_name = product_form_dict['name']
            product_dict = {}
            if product_form_dict['category']:
                product_dict['category'] = product_form_dict['category']
            if product_form_dict['price']:
                product_dict['price'] = product_form_dict['price']
            if product_form_dict['description']:
                product_dict['description'] = product_form_dict['description']
            if request.files.get('image').filename:
                image_name = 'images/' + request.files.get('image').filename
                product_dict['image'] = image_name
                photos.url(photos.save(request.files.get('image')))

            if product_dict:
                if product_name:
                    update_product = Product.query.filter_by(
                        name=product_name).first()
                    if product_form_dict['stock']:
                        existing_stock = update_product.stock
                        product_dict['stock'] = int(
                            product_form_dict['stock']) + existing_stock
                    if update_product:
                        Product.query.filter_by(
                            name=product_name).update(product_dict)
                        db.session.commit()
                        flash('Product was successfully updated', 'success')
                    else:
                        flash('No Product was found with the requested name',
                              'warning')
                else:
                    flash('Product Name is mandatory', 'warning')
            else:

                flash('No update was requested', 'warning')
            return redirect(url_for('admin'))
        return render_template('admin/update-product.html',
                               admin=True,
                               flag='update')
    else:
        flash('You are not allowed to access this page', 'warning')
        return render_template('index.html', logged_in_user=current_user)
Пример #11
0
def open_file(filename):
    file_url = photos.url(filename)  #获取文件的绝对路径
    flash('open success', category="info")
    if filename.split('.')[-1] == 'mp4':
        filepath = os.path.join('.\static\images', filename)
        return render_template('video.html',
                               filepath=filepath,
                               file_url=file_url)
    return render_template('browser.html', file_url=file_url)
Пример #12
0
 def display_image(self):
     '''the method returns an image url from a given filename
         in the database
     '''
     name = self.image_location
     image_url = photos.url(name)
     if not image_url:
         raise ValueError('can not have empty filename')
     return image_url
Пример #13
0
def upload_images():
    try:
        if request.method == 'POST' and 'photo' in request.files:
            filename = photos.save(request.files['photo'])
            file_url = photos.url(filename)
            blur_images = BlurModules(filename,
                                      int(request.form.get('radius'))).run()

            return responseAPIHelper(
                {
                    'original_image': file_url,
                    'blur_image': photos.url(blur_images)
                }, True), 200
        else:
            raise ValueError('Error Request')
    except BaseException as e:
        print(e)
        return responseAPIHelper({'Error': str(e)}, False), 200
Пример #14
0
def addPost():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        url = photos.url(filename)
        #u = url[21:36]
        u = url.replace("_uploads", "static")
        post = Post(img=u, author=current_user)
        db.session.add(post)
        db.session.commit()
    return render_template('addPost.html')
Пример #15
0
def profile():
    if request.method == 'POST':
        photo_name = photos.save(request.files.get('photo'))
        # update filename
        current_user.update_imagelocation(photo_name)
        flash('upload is a success')
        url = photos.url(photo_name)
        return render_template('owner_profile.html')

    return render_template('owner_profile.html')
Пример #16
0
def image_resize(image, base_width):
    #: create thumbnail
    filename, ext = os.path.splitext(image)
    img = Image.open(photos.path(image))
    if img.size[0] <= base_width:
        return photos.url(image)
    w_percent = (base_width / float(img.size[0]))
    h_size = int((float(img.size[1]) * float(w_percent)))
    img = img.resize((base_width, h_size), Image.ANTIALIAS)
    img.save(os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], filename + img_suffix[base_width] + ext))
    return url_for('main.uploaded_file', filename=filename + img_suffix[base_width] + ext, _external=True)
Пример #17
0
def add():
    if current_user.role == 'admin':
        form = AddProduct()
        if form.validate_on_submit():
            image_name = 'images/' + form.image.data.filename
            photos.url(photos.save(form.image.data))

            new_product = Product(name=form.name.data,
                                  category=form.category.data,
                                  price=form.price.data,
                                  stock=form.stock.data,
                                  description=form.description.data,
                                  image=image_name)

            db.session.add(new_product)
            db.session.commit()
            return redirect(url_for('admin'))
        return render_template('admin/add-product.html', admin=True, form=form)
    else:
        flash('You are not allowed to access this page', 'warning')
        return render_template('index.html', logged_in_user=current_user)
Пример #18
0
def upload():
    if request.method == 'POST' and 'image' in request.files:
        image = request.files['image']
        if image.filename == 'blob':
            image.filename = 'blob.png'
        # flask-upload 的新文件名称会以点的后缀判断是否需要扩展名
        new_name = uuid.uuid4().hex + '.'
        filename = photos.save(image, name=new_name)
        photos.config.base_url = '/static/uploads/file/'
        return jsonify(filename=photos.url(filename))
    else:
        return jsonify(msg='error upload'), 400
Пример #19
0
def update_pic():

    form = UpdatePic()
    user = User.query.filter_by(username=current_user.username).first()
    if form.validate():
        image_filename = photos.save(form.image.data)
        image_url = photos.url(image_filename)
        user.image =  image_url
        db.session.commit()
        return redirect(url_for('profile', username=current_user.username))
    flash('Something went wrong')
    return redirect(url_for('index'))
Пример #20
0
 def save_images(cls, files):  # this will return a list of url of photos
     images = []
     for img in files:
         # filename = hashlib.md5(current_user.username + str(time.time())).encode('UTF-8')
         # print(img)
         filename = hashlib.md5(str(
             time.time()).encode('UTF-8')).hexdigest()[:15]
         print(filename)
         name = photos.save(img, name=filename + '.')
         file_url = photos.url(name)
         print(file_url)
         images.append(file_url)
     return images
Пример #21
0
def upload_file():
    form = UploadForm()
    if form.validate_on_submit():
        filename = photos.save(form.photo.data,
                               folder='Avatar',
                               name=g.user.nickname + '.')
        file_url = photos.url(filename)
        g.user.imgurl = file_url
        db.session.add(g.user)
        db.session.commit()
        flash('修改成功.')
    else:
        file_url = None
    return render_template('img.html', form=form, file_url=file_url)
Пример #22
0
def register_race():
	title = "Race Registration"
	if current_user.is_anonymous:
		return redirect(url_for('index'))
	form = RegisterRaceForm()
	form.laps_number.choices = [(i, i) for i in range(1,11)]
	if form.validate_on_submit():
		filename = photos.save(form.logo.data)
		url = photos.url(filename)
		race = Race(form.name.data, url, form.admin.data, form.laps_number.data, form.distance.data, form.date_and_time_of_race.data, form.description.data, [], [])
		races_col.insert_one(race.__dict__)
		flash('Race {} is successfully registered.'.format(race.name))
		return redirect(url_for('races'))
	return render_template('register_race.html', form=form, title=title)
Пример #23
0
def edit_product(id):
    '''
	edit product
	'''
    check_admin()

    add_product = False

    product = Products.query.get_or_404(id)
    form = ProductsForm(obj=product)
    if form.validate_on_submit():
        filename = request.files['image']
        _, f_ext = os.path.splitext(filename.filename)

        name = form.name.data
        picture_fn = name + f_ext

        #get the name of the previous image
        previous_img_name = picture_fn

        photos.save(filename, name=picture_fn)
        url = photos.url(picture_fn)

        product.product_name = form.name.data
        product.product_price = form.price.data
        product.product_image = url
        product.product_description = form.description.data
        product.product_stock = form.stock.data
        db.session.commit()
        gc.collect()

        #remove the changed picture from the folder
        img_dir = Config.UPLOADED_PHOTOS_DEST + '/'
        os.remove(img_dir + previous_img_name)

        flash('You have successfully edited a product')
        #redirect to the products page
        redirect(url_for('admin.list_products'))

        form.name.data = product.product_name
        form.price.data = product.product_price
        form.image.data = product.product_image
        form.description.data = product.product_description
        form.stock.data = product.product_stock

    return render_template('admin/products/product.html',
                           add_product=add_product,
                           form=form,
                           title="Edit Product")
Пример #24
0
def create_topic():
    form = CreateTopicForm()
    if form.validate_on_submit():
        topic = Topic.create(title=form.title.data,
                             description=form.description.data)
        filename = photos.save(form.photo.data)
        photo_url = photos.url(form.photo.data)
        cover_url_sm = image_resize(filename, 30)
        cover_url = image_resize(filename, 400)
        topic.cover_url = cover_url
        topic.cover_url_sm = cover_url_sm
        db.session.add(topic)
        db.session.commit()
        return redirect(url_for('.topics'))
    return render_template('topic/create_topic.html', form=form)
Пример #25
0
def upload():
    form = PostForm()
    if form.validate_on_submit():
        image = form.photo.data
        filename = photos.save(image)
        file_url = photos.url(filename)
        post = Post(body=form.caption.data,
                    imagelink=file_url,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Uploaded your image!')
        return redirect(url_for('index'))

    return render_template('upload.html', form=form)
Пример #26
0
def addCat():
    '''添加一只猫'''
    form = addCatForm()
    if form.validate_on_submit():  #验证表单数据
        headimage = form.headimage.data
        a = photos.save(headimage)
        cat = catinfo(catname=form.catname.data,
                      birthday=form.birthday.data,
                      sex=form.sex.data,
                      headimage=photos.url(a),
                      status=1)
        db.session.add(cat)
        db.session.commit()
        flash('保存成功')
        return redirect(url_for('main.index'))
    return render_template('addcat.html', form=form)
Пример #27
0
def register():
    form = RegisterForm()

    if form.validate_on_submit():
        image_filename = photos.save(form.image.data)
        image_url = photos.url(image_filename)

        new_user = User(name=form.name.data,
                        username=form.username.data,
                        image=image_url,
                        password=generate_password_hash(form.password.data),
                        join_date=datetime.now()).save()

        return redirect(url_for('profile'))

    return render_template('register.html', form=form)
Пример #28
0
def add():
    
    form = AddProduct()

    products = Product.query.all()
    if form.validate_on_submit():
        image_url = photos.url(photos.save(form.image.data))
        new_product = Product(name=form.name.data, price=form.price.data, \
                            stock=form.stock.data, description=form.description.data, \
                            image=image_url)
        db.session.add(new_product)
        db.session.commit()

        flash('You added a new product')
        return redirect(url_for('admin'))
    return render_template('admin/add-product.html', admin=True, form=form, products=products)
Пример #29
0
def edit_profile():
	form = EditProfileForm(current_user.username, current_user.email)
	if form.validate_on_submit():
		current_user.username = form.username.data
		current_user.about_me = form.about_me.data
		current_user.email = form.email.data
		if form.profile_pic.data:
			profile_pic_filename = photos.save(form.profile_pic.data)
			current_user.profile_pic = photos.url(profile_pic_filename)
		db.session.commit()
		flash('Your changes have been saved.')
		return redirect(url_for('user', username=current_user.username))
	elif request.method == 'GET':
		form.username.data = current_user.username
		form.about_me.data = current_user.about_me
		form.email.data = current_user.email
	return render_template('edit_profile.html', title='Edit Profile', form=form)
Пример #30
0
def upload_avatar():
    s = search()
    if s:
        return s
    form = UploadForm()
    if form.validate_on_submit():
        photoname = photos.save(form.photo.data)

        photo_url = photos.url(photoname)  # 原图
        avatar_url_sm = image_resize(photoname, 30)
        avatar_url_nm = image_resize(photoname, 400)
        current_user.avatar_url_sm = avatar_url_sm  # 缩略头像
        current_user.avatar_url_nm = avatar_url_nm  # 正常头像
        db.session.add(current_user)
    else:
        photo_url = None
    return render_template('index/upload.html', form=form, file_url=photo_url)
Пример #31
0
def edit_profile():
    form = EditProfileUserForm()
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.email = form.email.data
        filename = photos.save(form.profile_picture.data)
        current_user.profile_picture = photos.url(filename)
        current_user.address = form.address.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user)
        # if form.profile_picture.data is None:
        #     flash(photos)
        return redirect(url_for('main.user', username=current_user.username))
    form.username.data = current_user.username
    form.address.data = current_user.address
    form.about_me.data = current_user.about_me
    return render_template('profile/edit_profile.html', form=form)
Пример #32
0
def ckupload():
    t = {}
    uploaded = False

    if request.method == 'POST' and 'upload' in request.files:
        fileobj = request.files['upload']
        # 生成随机的文件名
        suffix = os.path.splitext(fileobj.filename)[1]
        filename = 'static/uploads/temp/' + gen_rnd_filename() + suffix
        photos.save(fileobj, name=filename)
        url = photos.url(filename)
        uploaded = True
        t['url'] = '/' + filename
    else:
        t['error']['message'] = 'could not upload this image'
    t['uploaded'] = uploaded

    return json.dumps(t)
Пример #33
0
def upload():
    """
    Upload a post
    Use Flask-Uploads for photo uploads
    :return: a redirect to write
    """
    form = request.form
    print request.files
    if request.method == 'POST' and 'photo' in request.files:
        pic = request.files['photo']
        filename = photos.save(pic)
        user = session['user']
        url = photos.url(filename)
        rec = models.Photo(filename=filename, user=user, url=url)
        db.session.add(rec)
        db.session.commit()
        if form is not None:
            res = add_post_to_db(form['content'], url)
            print res
        else:
            print "nothing to add to db"
    return redirect(url_for('write'))