Ejemplo n.º 1
0
def upload():
    """图片上传处理"""
    file = request.files.get('file')
    if not allowed_file(file.filename):
        res = {'code': 0, 'msg': '图片格式异常'}
    else:
        url_path = ''
        upload_type = current_app.config.get('H3BLOG_UPLOAD_TYPE')
        ex = os.path.splitext(file.filename)[1]
        filename = datetime.now().strftime('%Y%m%d%H%M%S') + ex
        if upload_type is None or upload_type == '' or upload_type == 'local':
            file.save(
                os.path.join(current_app.config['H3BLOG_UPLOAD_PATH'],
                             filename))
            url_path = url_for('admin.get_image', filename=filename)
        elif upload_type == 'qiniu':
            try:
                qiniu_cdn_url = current_app.config.get('QINIU_CDN_URL')
                url_path = qiniu_cdn_url + upload_file_qiniu(
                    file.read(), filename)
            except Exception as e:
                return jsonify({'success': 0, 'message': '上传图片异常'})
        #返回
        pic = Picture(
            name=file.filename if len(file.filename) < 32 else filename,
            url=url_path)
        db.session.add(pic)
        res = {'code': 1, 'msg': u'图片上传成功', 'url': url_path}
    return jsonify(res)
Ejemplo n.º 2
0
def update_role():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part', 'error')
            return redirect(url_for('data.update_role'))
        file = request.files['file']
        if file.filename == '':
            flash('No selected file', 'error')
            return redirect(request.url)
        if file:
            if allowed_file(file.filename,
                            current_app.config['ALLOWED_EXTENSIONS']):
                fn = upload_csv_file(file, 'role', 'role-csv')
                process_role.delay(fn)
                flash('File Uploaded Successfully', 'success')
            else:
                flash('Invalid File Type', 'error')
    return render_template('data/update_role.html', title='Home')
Ejemplo n.º 3
0
def sign_s3():
    S3_BUCKET = os.environ.get('S3_BUCKET')

    file_name = request.args.get('file_name')
    file_type = request.args.get('file_type')

    if allowed_file(file_name):
        parts_of_filename = secure_filename(file_name).rsplit('.', 1)
        file_name = '.'.join([
            pbkdf2_hex(parts_of_filename[0] + str(time.time()),
                       app.config['SECURITY_PASSWORD_SALT']),
            parts_of_filename[1]
        ])
    else:
        return json.dumps({'data': 'Bad file type'})

    s3 = boto3.client('s3')

    presigned_post = s3.generate_presigned_post(Bucket=S3_BUCKET,
                                                Key=file_name,
                                                Fields={
                                                    "acl": "public-read",
                                                    "Content-Type": file_type
                                                },
                                                Conditions=[{
                                                    "acl":
                                                    "public-read"
                                                }, {
                                                    "Content-Type":
                                                    file_type
                                                }],
                                                ExpiresIn=3600)

    return json.dumps({
        'data':
        presigned_post,
        'url':
        'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name)
    })
Ejemplo n.º 4
0
def upload_data():
    file_final_name = request.values.get('fileName')
    update_signal = request.values.getlist('updateSignal')
    file = request.files['file']
    if not file:
        res = {
            'status': 0,
            'msg': '请选择文件'
        }
        return jsonify(res)
    file_name = file.filename
    if not allowed_file(file_name):
        res = {
            'status': 0,
            'msg': '文件格式不正确'
        }
        return jsonify(res)
    else:
        file_extend = file_name.rsplit('.', 1)[1]
        if file_extend == 'xls' or file_extend == 'xlsx':
            df = pd.read_excel(file)
        else:
            df = pd.read_csv(file)
        cols = df.columns.values.tolist()
        df['file_name'] = file_final_name
        records = json.loads(df.T.to_json()).values()
        if update_signal:
            mongo.db.base_datas.delete_many({'file_name': file_final_name})
            mongo.db.base_datas.insert(records)
            mongo.db.base_features.delete_many({'file_name': file_final_name})
            mongo.db.base_features.insert({'file_name': file_final_name, 'cols': cols})
        else:
            mongo.db.base_datas.insert(records)
            mongo.db.base_features.insert({'file_name': file_final_name, 'cols': cols})

        res = {
            'status': 1,
        }
        return jsonify(res)
Ejemplo n.º 5
0
def index():
    errors = []
    if request.method == 'POST':
        try:
            file = request.files["img_input"]
            if file.filename == "":
                errors.append('No file provided')
            elif file:
                if not allowed_file(file.filename):
                    errors.append(
                        'File type not allowed. Only image files with the following extensions are accepted:'
                        ' %s' % str(IMAGES))
                else:
                    file.filename = secure_filename(file.filename)
                    output = upload_file_to_s3(file,
                                               app.config["S3_BUCKET_NAME"])
                    return render_template('img.html', image=output)
        except Exception as e:
            errors.append(
                str(e) +
                ' Possible reasons: No file provided, Invalid file type, File not found.'
            )
    return render_template('index.html', errors=errors)
Ejemplo n.º 6
0
def create_user():

    form = FormCreateUser()
    
    roles = Role.query.all()
    user_role = next((x for x in roles if x.name == USER), None)

    if form.validate_on_submit():

        user = User(
            name=form.name.data.strip(),
            phone=form.phone.data.strip(),
            email=form.email.data.strip(),
            password=form.password.data.strip(),
            confirmed=True
        )

        # assign role as normal user
        
        role_ids = zip(request.form.getlist("roles"))
        found_user_role = False
        for role_id in role_ids:
            find_role = next((x for x in roles if x.id == int(role_id[0])), None)
            if find_role:
                user.roles.append(find_role)
            if find_role.id == user_role:
                found_user_role = True

        if found_user_role is False:
            user.roles.append(user_role)

        # validate photo upload extension
        file_name = None
        if form.photo.data:
            file_name = secure_filename(form.photo.data.filename)
        if file_name and not util.allowed_file(file_name, app.config["ALLOWED_EXTENSIONS"]):
            flash("photo upload allows only {}".format(",".join(app.config["ALLOWED_EXTENSIONS"])))
            return redirect(url_for("userbe.create_user"))
        
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as err:
            logger.exception(err)
            flash("can not create user at this moment", "negative")
            return redirect(url_for("userbe.create_user"))

        if file_name:
                
            # check if parent dir exist
            parent_dir = os.path.join("app", app.config["UPLOAD_FOLDER"], 
                    "users", "{}".format(user.id), "photo")
            if not os.path.exists(parent_dir):
                os.makedirs(parent_dir)

            # if file for new logo already exists
            new_logo = os.path.join(parent_dir, "{0}".format(file_name))
            if os.path.isfile(new_logo):
                os.remove(new_logo)

            # save new logo to file
            form.photo.data.save(new_logo)

            user.photo = file_name

            try:
                db.session.commit()
            except Exception as err:
                logger.exception(err)
                flash("can not create user at this moment", "negative")
                return redirect(url_for("userbe.create_user"))

        flash("user = {0} is created".format(user.name), "positive")

        return redirect(url_for("userbe.search_users_results", is_advanced=0, keyword=util.EMPTY,
                                sorted_by=util.DEFAULT_SORT, sorted_as="desc", per_page=10, page=1,
                                id_to_filter=util.EMPTY, name_to_filter=util.EMPTY, email_to_filter=util.EMPTY,
                                phone_to_filter=util.EMPTY, confirmed_to_filter=util.EMPTY,
                                deleted_to_filter=util.EMPTY, role_to_filter=util.EMPTY))

    return render_template("backend/user/create.html", title="Create User", form=form, roles=roles, user_role=user_role)
Ejemplo n.º 7
0
def edit_user(id):
    
    user = User.query.options(lazyload(User.roles)).filter_by(id=id).first()
    if not user:
        abort(404)

    roles = Role.query.all()
    user_role = next((x for x in roles if x.name == USER), None)
    
    form = FormEditProfileForAdmin()

    if request.method == "GET":
        form.name.data = user.name
        form.phone.data = user.phone
        form.email.data = user.email

    if form.validate_on_submit():

        # validate photo upload extension
        file_name = None
        if form.photo.data:
            file_name = secure_filename(form.photo.data.filename)
        if file_name and not util.allowed_file(file_name, app.config["ALLOWED_EXTENSIONS"]):
            flash("photo upload allows only {}".format(",".join(app.config["ALLOWED_EXTENSIONS"])))
            return redirect(url_for("userbe.edit_user", id=user.id))

        # properties setter
        changed = False
        if user.name != form.name.data.strip():
            user.name = form.name.data.strip()
            changed = True

        if form.phone.data and user.phone != form.phone.data.strip():
            user.phone = form.phone.data.strip()
            changed = True

        if form.password.data and user.check_password(form.password.data.strip()) is False:
            user.password = form.password.data.strip()
            changed = True
            
        role_ids = request.form.getlist("roles")

        not_user_roles = []
        for role_id in role_ids:
            print("given role id = {0}, user_role.id = {1}".format(role_id, user_role.id))
            if int(role_id) != user_role.id:
                find_role = next((x for x in roles if x.id == int(role_id)), None)
                if find_role:
                    not_user_roles.append(find_role)

        for not_user_role in not_user_roles:
            find_role = next((x for x in user.roles if x.id == not_user_role.id and x.id != user_role.id), None)
            if find_role is None:
                user.roles.append(not_user_role)
                changed = True

        for role in user.roles:
            if role.id != user_role.id:
                find_role = next((x for x in not_user_roles if x.id == role.id), None)
                if find_role is None:
                    user.roles.remove(role)
                    changed = True

        if changed is True:
            try:
                db.session.commit()
            except Exception as err:
                logger.exception(err)
                flash("can not edit user by name = {}".format(user.name), "negative")
                return redirect(url_for("userbe.edit_user", id=id))

        if file_name and file_name != user.photo:

            changed = True
                
            # check if parent dir exist
            parent_dir = os.path.join("app", app.config["UPLOAD_FOLDER"], "users", "{}".format(user.id), "photo")
            if not os.path.exists(parent_dir):
                os.makedirs(parent_dir)

            # remove current photo
            current_photo = os.path.join(parent_dir, "{0}".format(user.photo))
            if os.path.isfile(current_photo):
                os.remove(current_photo)
            
            # if file for new photo already exists
            new_photo = os.path.join(parent_dir, "{0}".format(file_name))
            if os.path.isfile(new_photo):
                os.remove(new_photo)

            # save new logo to file
            form.photo.data.save(new_photo)

            user.photo = file_name
            db.session.commit()
                
        if changed is False:
            flash("data is not changed", "negative")
            return redirect(url_for("userbe.edit_user", id=id))
        else:
            flash("user by name = {0} is updated".format(user.name), "positive")

            return redirect(url_for("userbe.search_users_results", is_advanced=0, keyword=util.EMPTY,
                                    sorted_by=util.DEFAULT_SORT, sorted_as="desc", per_page=10, page=1,
                                    id_to_filter=util.EMPTY, name_to_filter=util.EMPTY, email_to_filter=util.EMPTY,
                                    phone_to_filter=util.EMPTY, confirmed_to_filter=util.EMPTY,
                                    deleted_to_filter=util.EMPTY, role_to_filter=util.EMPTY))
        
    return render_template("backend/user/edit.html", title="Edit User", form=form,
                           roles=roles, user=user, user_role=user_role)