def face_swap_api():

    if 'files' not in request.files:
        return Response({'error': 'No files selected'}, status=412)

    files = request.files.getlist('files')

    if len(files) != 2:
        return Response({'error': 'Select Two Faces (Images)'}, status=412)

    face_one = files[0]
    face_two = files[1]

    if allowed_file(face_one.filename) and allowed_file(face_two.filename):
        f1_image = file2image(face_one)
        f2_image = file2image(face_two)

        logger.info(f'Running FaceSwap')
        swapped_face = swap_faces(f1_image, f2_image)

        # convert it to bytes
        b64_image = image2b64(swapped_face)

        return jsonify(b64_image), 200

    else:
        return Response({'error': f'{face_one.mimetype} not allowed'},
                        status=412)
Exemplo n.º 2
0
    def test_utils(self):
        app.config['ENV'] = 'TESTING'
        # allowing files types
        self.assertTrue(utils.allowed_file('filename.jpg'))
        self.assertFalse(utils.allowed_file('filename.gif'))
        self.assertTrue(utils.allowed_file('filename.png'))
        self.assertFalse(utils.allowed_file('filename.pdf'))

        # search file function
        self.assertTrue(utils.find_file('1.jpg'))
        self.assertTrue(utils.find_file('2.jpg'))
        self.assertFalse(utils.find_file('3.jpg'))

        # download function
        file = utils._download(
            'http://www.reportingday.com/wp-content/uploads/2018/06/Cat-Sleeping-Pics.jpg'
        )
        self.assertTrue(file['success'])
        self.assertEqual(file['name'], file['name'])

        # remove function
        self.assertTrue(utils.remove_file(file['name']))
        self.assertFalse(utils.remove_file('randomanme.jpg'))

        # predict function
        self.assertEqual(utils.make_prediction('1.jpg'), 'dog')
        self.assertEqual(utils.make_prediction('2.jpg'), 'cat')
        self.assertRaises(FileNotFoundError, utils.make_prediction, 'asd.jpg')
Exemplo n.º 3
0
    def allowed_file(self):
        # Valid cases
        assert_true(allowed_file('a.csv'), True)
        assert_true(allowed_file('_@#b1.csv'), True)
        assert_true(allowed_file('a.txt'), True)
        assert_true(allowed_file('_@#b1.txt'), True)
        assert_true(allowed_file('_@#b1.csv'), True)

        assert_true(allowed_file('_@#b1'), False)
        assert_true(allowed_file('csv'), False)
        assert_true(allowed_file('txt'), False)
        assert_true(allowed_file('a.jpg'), False)
Exemplo n.º 4
0
    def upload():

        if 'client' in config and 'user' in config["client"] and 'pass' in config["client"]:
            auth_control = check_auth(config)
            if auth_control:
                return auth_control

        _file = request.files.get("file")
        if not _file:
            return "a file named as 'file' required", 400

        if not allowed_file(_file.filename, config):
            return "invalid file type", 400

        filename = secure_filename(_file.filename)
        full_filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)

        try:
            full_filename = get_available_filename(full_filename)
        except ValueError as error:
            return error.message, 400

        _file.save(full_filename)

        return os.path.split(full_filename)[1], 201
def index():

    # check if the post request has the file part
    if FILENAME not in request.files:
        return failure("Field with name {} was not submitted".format(FILENAME))

    file = request.files[FILENAME]

    # if user does not select file, browser also
    # submit a empty part without filename
    if file:
        if file.filename == '':
            return failure("No file was selected")

        if allowed_file(file.filename, 'tar'):

            # Create a new job for this tar file
            job = create_job(file.filename)
            filepath = job.to_filepath()
            print("Saving to: {}".format(filepath))
            file.save(filepath)

            # Update the job now that the tarfile has been saved
            update_job_state(job, state=JobState.TAR_SAVED)
            return SUCCESS
    return failure("No file was selected or file is not a .tar file.")
Exemplo n.º 6
0
def upload():
    if request.method == 'GET':
        return render_template('upload.html')
    elif request.method == 'POST':
        uploaded_file = request.files['file']

        if uploaded_file and utils.allowed_file(uploaded_file.filename):
            filename = secure_filename(uploaded_file.filename)
            full_path = os.path.join(app.config['UPLOAD_DIR'], filename)
            uploaded_file.save(full_path)

            with open(full_path, 'rb') as f:
                exif_data = exifread.process_file(f)
                utils.process_exif(exif_data, filename)

                return jsonify(dict(
                    album_path=url_for('compare', image=filename)
                    ))

        else:
            allowed = ', '.join(app.config['ALLOWED_EXTENSIONS'])
            response = jsonify(dict(
                error="File does not match allowed extensions: %s" % allowed))
            response.status_code = 500
            return response
Exemplo n.º 7
0
    def post(self):

        form = AddItemForm()
        item = Item()

        if form.validate_on_submit():
            ar_title = Titles()
            fr_title = Titles()
            en_title = Titles()

            ar_title.title = form.ar_title.data.strip()
            ar_title.lang = 'ar'

            fr_title.title = form.fr_title.data.strip()
            fr_title.lang = 'fr'

            en_title.title = form.en_title.data.strip()
            en_title.lang = 'en'

            item.titles.append(ar_title)
            item.titles.append(fr_title)
            item.titles.append(en_title)

            item.description = form.description.data

            item.submitter = User.objects.get(id=current_user.id)

        else:
            flash('upload unsuccessful', 'error')
            return render_template('items/add_item.html', form=form)

        uploaded_files = request.files.getlist("files")
        thumbnail = request.files['thumbnail']

        thumbnail_name = secure_filename(thumbnail.filename)

        if thumbnail and allowed_thumbnails(thumbnail_name):
            ext = thumbnail.mimetype.split('/')[-1]
            # use the 'thumbnail' name for all thumbnails
            filename = '.'.join(["thumbnail", ext])
            item.thumbnail.put(thumbnail.stream,
                               content_type=thumbnail.mimetype,
                               filename=filename)

        for file in uploaded_files:
            # Make the filename safe, remove unsupported chars
            filename = secure_filename(file.filename)
            # Check if the file is one of the allowed types/extensions
            if file and allowed_file(filename):
                # put the file in the ListField.
                # see https://gist.github.com/tfausak/1299339
                file_ = GridFSProxy()
                file_.put(file.stream,
                          content_type=file.mimetype,
                          filename=filename)
                item.files.append(file_)
        # Save the thing
        item.save()
        flash('upload successful')
        return render_template('items/add_item.html', form=form)
def upload_file():
    if request.method == 'POST':

        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']

        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)

            # Upload file to cloud storage
            upload_cloud(bucket_name, filename, filepath)

            # Open image file and convert to required formats
            img, upl_img = convert_img(file)

            # Get prediction from AutoML model
            prediction = get_prediction(img, project_id, model_id)

            # Convert prediction received from model into readable results
            response = lbl_score(prediction)

            return render_template('predict.html', data=response, img=upl_img)
    return render_template('index.html')
Exemplo n.º 9
0
 def post(self):
     args = self.parser.parse_args()
     image = args.get('image')
     imgB64 = args.get('imgB64')
     array = None
     if not image and not imgB64:
         return {"message": "No image or base64 string"}, 200
     elif imgB64:
         try:
             array = convert_b64(imgB64)
         except Exception as e:
             print(e)
             abort(400, message="decode base64 fail.")
     elif image:
         if not image.filename:
             return {"message": "No image selected."}
         if not allowed_file(image.filename):
             return {"message": "The file must be image type."}
         try:
             array = read_image(image)
         except Exception as e:
             print(e)
             abort(400, message="Something wrong")
     result = onnx_predict(sess, array)
     return {"message": 'success',
             "result": str(result)}, 200
Exemplo n.º 10
0
    def upload():
        """
        An endpoint for uploading micromeda files.
        """
        global REDIS_CACHE

        file = request.files['file']

        if allowed_file(file.filename):
            filename = secure_filename(file.filename)
            out_path = os.path.join(flask_app.config['UPLOAD_FOLDER'],
                                    filename)
            file.save(out_path)
            result = extract_results_from_micromeda_file(
                out_path, flask_app.config['PROPERTIES_TREE'])
            os.remove(out_path)

            result_ttl = flask_app.config['CACHE_TTL']
            flask_app.logger.info(
                "Caching micromeda file for {} seconds".format(result_ttl))
            result_key = cache_result(result,
                                      REDIS_CACHE,
                                      cache_ttl=result_ttl)
            response = jsonify({'result_key': result_key})
        else:
            response = flask_app.response_class(response='Upload failed',
                                                status=404)

        return response
Exemplo n.º 11
0
def submit_lease_for_analysis():
    if "file" not in request.files:
        return {"status": "failed", "message": "No file provided"}

    lease_doc = request.files["file"]

    if lease_doc and allowed_file(lease_doc.filename):
        filename = secure_filename(lease_doc.filename)
        filepath = os.path.join(app.config["LEASE_DOCS_FOLDER"], filename)
        lease_doc.save(filepath)

        infra = init_infrastucture()

        submit_lease_for_analysis = SubmitLeaseForAnalysis(infra["Storage"])
        response = submit_lease_for_analysis.execute(
            Request({
                "lease_file_path": filepath,
                "file_name": filename
            }))

        # Celery needs a String instead of an ObjectId
        lease_id = str(response.data["Lease"]["Id"])
        task_extract_paragraphs.delay(lease_id, filepath)
        task_get_lease_thumbnail.delay(lease_id, filepath)

        return Response(json.dumps(response.data, default=str),
                        mimetype="application/json")

    return {"status": "failed", "message": "invalid file"}
Exemplo n.º 12
0
def video() -> str:
    file = request.files['file']
    if not file:
        return "Unable to fund a file key in the body of the request."

    if not allowed_file(file.filename):
        return "Unsupported video extension {:s}".format(file.filename)

    filename = secure_filename(file.filename)
    path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(path)

    try:
        height, width, fps, frame_count = process_video(path)
    except IOError as err:
        os.remove(path)  # clean up
        return str(err)

    os.remove(path)  # clean up

    time_stamp = datetime.now().strftime(TIME_STAMP_FORMAT)
    meta = (time_stamp, filename, height, width, fps, frame_count)

    insert_into_db(meta)  # TODO: add try/except

    return json.dumps(meta)
Exemplo n.º 13
0
def upload():
    if request.method == 'GET':
        return render_template('upload.html')
    elif request.method == 'POST':
        uploaded_file = request.files['file']

        if uploaded_file and utils.allowed_file(uploaded_file.filename):
            filename = secure_filename(uploaded_file.filename)
            full_path = os.path.join(app.config['UPLOAD_DIR'], filename)
            uploaded_file.save(full_path)

            with open(full_path, 'rb') as f:
                exif_data = exifread.process_file(f)
                utils.process_exif(exif_data, filename)

                return jsonify(
                    dict(album_path=url_for('compare', image=filename)))

        else:
            allowed = ', '.join(app.config['ALLOWED_EXTENSIONS'])
            response = jsonify(
                dict(error="File does not match allowed extensions: %s" %
                     allowed))
            response.status_code = 500
            return response
Exemplo n.º 14
0
def upload_image():
    form = request.form
    key = form['key']
    name = form['name']
    data = request.files
    file = data['uploadFile']
    if key != password:
        return jsonify({'state': 1})
    if file:
        if name and re.match(r'^([a-zA-Z][a-zA-Z0-9_]*)$', name):
            if name.rfind('.') != -1:
                filename = name
            else:
                filename = name.rsplit('.', 1)[0] + '.' + file.filename.rsplit('.', 1)[1]
        elif allowed_file(file.filename):
            filename = file.filename
        else:
            return jsonify({
                'state': 2
            })
        file.save(os.path.join(UPLOAD_FOLDER, filename))
        return jsonify({
            'state': 0,
            'url': request.url.rsplit('/', 1)[0] + '/image/' + filename
        })
    return jsonify({'state': 3})
Exemplo n.º 15
0
def upload(todo_id, page):
    forms = AttatchForm(csrf_enabled=True)
    forms.page = page
    forms.todo_id = todo_id
    attatches = Attatch.query.filter(Attatch.todo_id == todo_id).all()
    forms.attatches = attatches

    if forms.validate_on_submit():
        file_dir = get_uploaddir()
        f = request.files['uploadfile']  # 从表单的file字段获取文件,myfile为该表单的name值
        if f and allowed_file(f.filename):  # 判断是否是允许上传的文件类型
            fname = f.filename
            ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
            #unix_time = int(time.time())
            fn = datetime.now().strftime('%Y%m%d%H%M%S')
            fn = fn + '_%d' % random.randint(0, 100)
            new_filename = fn + '.' + ext  # 修改文件名
            f.save(os.path.join(file_dir, new_filename))  # 保存文件到upload目录
            att = Attatch()
            att.sourcename = secure_filename(fname)
            att.todo_id = todo_id
            att.own_id = session.get('user_id')
            att.filepath = new_filename
            db.session.add(att)
            db.session.commit()
            flash("上传附件成功", 'ok')
            return redirect(url_for('edit', page=page, id=todo_id))
        else:
            flash("上传失败", 'error')
            return redirect(url_for('edit', page=page, id=todo_id))
    else:
        return render_template('upload.html', forms=forms)
Exemplo n.º 16
0
def upload():
    """
    Uploads a file to the upload folder from the upload.html page
    """
    if request.method == 'POST':
        ticket_number = request.args.get('ticket_number')
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        requested_file = request.files['file']
        if requested_file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if requested_file and allowed_file(requested_file.filename):
            file_ext = requested_file.filename.rsplit('.', 1)[1]
            file_save_name = 'signedform_ticket_{}.{}'.format(
                ticket_number, file_ext
            )
            file_save_path = os.path.join(
                APP.config['UPLOAD_FOLDER'], file_save_name
            )
            requested_file.save(file_save_path)

            send_mail(
                APP, MAIL, 
                "*****@*****.**",
                "[form upload] Creative Commons Consent Form | MeldeyDB Manager",
                " ",
                attachment=file_save_path
            )

        return redirect(url_for('thankyou'))
Exemplo n.º 17
0
def upload_test_image():
    if request.method == 'POST':
        # check if post request has the file
        if 'file' not in request.files:
            flash('No file.')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submits empty part without filename
        if file.filename == '':
            flash('No selected file.')
            return redirect(request.url)
        # valid file uploaded by user
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            model = load_model(PATH_TO_SAVED_MODEL, MODEL_NAME)
            prediction = predict(model, filepath)
            return render_template('results.html',
                                   prediction=prediction,
                                   filename=filename)
    # clear /tmp folder
    for f in glob.glob(os.path.join(app.config['UPLOAD_FOLDER'], '*')):
        os.remove(f)
    return render_template('index.html')
Exemplo n.º 18
0
def upload_image():
    f = request.files.get('upload')
    if not allowed_file(f.filename):
        return upload_fail('Image only!')
    f.save(os.path.join(current_app.config['FLASKBLOG_UPLOAD_PATH'], f.filename))
    url = url_for('.get_image', filename=f.filename)
    return upload_success(url, f.filename)
Exemplo n.º 19
0
def handle_file_upload(files):
    """upload service"""
    logger.info('uploading file')

    try:
        # check if the post request has the file part
        assert ('file' in files), "No file part"

        file = files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        assert (file.filename != ''), "No selected file"

        assert (allowed_file(file.filename,
                             ALLOWED_EXTENSIONS)), "Not allowed extention"

        filename = secure_filename(file.filename)
        path = os.path.join(os.getcwd(), 'uploads', filename)

        file.save(path)
        logger.info('file uploaded ... ✓')
        return path
    except AssertionError as err:
        logger.error('error while uploading file :', err)
        raise err
Exemplo n.º 20
0
    def upload():

        if 'client' in config and 'user' in config[
                "client"] and 'pass' in config["client"]:
            auth_control = check_auth(config)
            if auth_control:
                return auth_control

        _file = request.files.get("file")
        if not _file:
            return "a file named as 'file' required", 400

        if not allowed_file(_file.filename, config):
            return "invalid file type", 400

        filename = secure_filename(_file.filename)
        full_filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)

        try:
            full_filename = get_available_filename(full_filename)
        except ValueError as error:
            return error.message, 400

        _file.save(full_filename)

        return os.path.split(full_filename)[1], 201
Exemplo n.º 21
0
def change_profile_img_route():
    kp_id = request.form['kp_id']
    f = request.files['profile_image']

    if not kp_id or not f:
        return jsonify(msg='Bad request'), 400

    if f.filename == '':
        return jsonify(msg='No selected image'), 400
    if not allowed_file(f.filename):
        return jsonify(msg='Please selected image'), 400

    know_people = list_know_people_by_id(kp_id)

    images_dir = path.join(getcwd(), 'images')
    if not path.exists(images_dir):
        mkdir(images_dir)

    profile_image_path = path.join(images_dir, secure_filename(f.filename))
    if not change_profile_img(kp_id=kp_id,
                              profile_image=secure_filename(f.filename)):
        return jsonify(msg='change profile image failed'), 400
    try:
        if len(know_people) > 0:
            profile_image = path.join(images_dir,
                                      secure_filename(know_people[0][5]))
            if path.exists(profile_image):
                remove(profile_image)
    except:
        print("Delete old image failed")

    f.save(profile_image_path)
    return jsonify(msg='change profile image success'), 200
Exemplo n.º 22
0
def classify_image_api(model_handle="resnet34-imagenet") -> Response:
    """

    Args:
        model_handle: the model handle string, should be in `models.model_handler.MODEL_REGISTER`

    Returns:
        (Response): if error then a json of {'error': 'message'} is sent
                    else return a json of sorted List[Dict[{'class_idx': idx, 'class_name': cn, 'confidence': 'c'}]]
    """
    if model_handle not in MODEL_REGISTER:
        return Response(
            {"error": f"{model_handle} not found in registered models"},
            status=404)

    if "file" not in request.files:
        return Response({"error": "No file part"}, status=412)

    file: FileStorage = request.files["file"]

    if file.filename == "":
        return Response({"error": "No file selected"}, status=417)

    if allowed_file(file.filename):
        image: Image = file2image(file)
        classifier = get_classifier(model_handle)
        output = classifier(image)
        return Response(json.dumps(output), status=200)

    else:
        return Response({"error": f"{file.mimetype} not allowed"}, status=412)
Exemplo n.º 23
0
    def create_image():
        if 'file' not in request.files:
            abort(400)

        file = request.files['file']

        if file.filename == '':
            abort(400)

        if file and allowed_file(file.filename):
            try:
                filename = secure_filename(file.filename)
                filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                filetype = filename.split(".")[-1]
                file.save(filepath)

                image = Image(filepath, filename, filetype)
                image.insert()

                return jsonify({
                    'success': True,
                    'image': image.format()

                })
            except BaseException:
                abort(422)
Exemplo n.º 24
0
def setting():
    if redirect_is_not_logged(session) != True:
        return redirect_is_not_logged(session)
    page_name = "Setting"
    valid = True
    success_message_p = ''
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            valid = False

        if valid:

            file = request.files['file']

            if file.filename == '':
                valid = False
            if file and allowed_file(file.filename, ALLOWED_EXTENSIONS):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                user = User.query.filter_by(id=session['id']).first()
                user.profil_media = filename
                db.session.commit()
                success_message_p = "Profile Updated"
                session['profil_media'] = filename

    return render_template('settings.html',
                           page_name=page_name,
                           session=session,
                           success_message_p=success_message_p)
Exemplo n.º 25
0
def insert_recipe():
    """ When the user clicks to add the new recipe """
    recipes = mongo.db.recipes
    image = request.files['image']
    path = ""

    """ Checks if there is an image and if that image is of the allowed filetype """
    if image and allowed_file(image.filename):
        """ Sets the path with the image and a random string to make it unique, then saves the image to that path """
        path = "static/images/" + get_random_string() + image.filename
        image.save(path)

    """ Takes the prep_time and cooking_time from the form as integers then adds them together to get the total time """
    prep_time = int(request.form.get('prep_time'))
    cooking_time = int(request.form.get('cooking_time'))
    total_time = prep_time + cooking_time

    """ Takes the required fields from the form and makes a new entry to the database """
    """ Sets the image to the path if the image exists and is allowed, if not it will set the image to none """
    recipes.insert_one(
        {
            'recipe_name': request.form.get('recipe_name'),
            'recipe_description': request.form.get('description'),
            'prep_time': prep_time,
            'cooking_time': cooking_time,
            'total_time': total_time,
            'difficulty': request.form.get('difficulty'),
            'serves': request.form.get('serves'),
            'recipe_image': f"{path}" if path else None,
            'ingredients': request.form.getlist('ingredients'),
            'methods': request.form.getlist('methods')
        }
    )
    """ Once created redirects to the Home Page """
    return redirect(url_for('get_recipes'))
Exemplo n.º 26
0
def upload_data():
    file = request.files['file']
    if file and allowed_file(file.filename):
        file_path = os.path.join(app.config['DATA_DIR'], VkrInstance.data_file)
        # бэкап старого файла
        shutil.copyfile(os.path.join(app.config['DATA_DIR'], VkrInstance.data_file),
                  os.path.join(app.config['DATA_DIR'], 'old_' + VkrInstance.data_file))
        file.save(file_path)

        # Удаляем старые pickle-файлы
        clear_pickle_files(app.config['DATA_DIR'])
        # Перечитаем файл с данными
        # VkrInstance.init()
        print("lol")
        return jsonify({
            'status': 'success',
            'result': {
                'file_path': file_path
            }
        })
    else:
        return jsonify({
            'status': 'error',
            'result': {
                'message': 'Неподходящий тип файла'
            }
        })
Exemplo n.º 27
0
def get_human_pose() -> Response:
    """

    Handles the human pose POST request, takes the pose image and identifies the human pose keypoints,
        stitches them together and returns a response with the image as b64 encoded, with the detected human pose

    Returns:
        (Response): b64 image string with the detected human pose

    """
    from models import get_pose

    if "file" not in request.files:
        return Response({"error": "No file part"}, status=412)

    file: FileStorage = request.files["file"]

    if file.filename == "":
        return Response({"error": "No file selected"}, status=417)

    if allowed_file(file.filename):
        image: Image = file2image(file)
        pose_img = get_pose(image)

        # convert it to b64 bytes
        b64_pose = image2b64(pose_img)

        return jsonify(b64_pose), 200

    else:
        return Response({"error": f"{file.mimetype} not allowed"}, status=412)
Exemplo n.º 28
0
def upload_resource():
    if 'file' not in request.files:
        abort(400, 'no file has been uploaded.')
    file = request.files['file']
    if file.filename == '':
        abort(400, 'no file has been uploaded')

    file_extension = get_file_extension(file.filename)
    if file and allowed_file(file_extension,
                             current_app.config['ALLOWED_EXTENSIONS']):
        ret = upload_file_to_qiniu(current_app.config['QINIU_ACCESS_KEY'],
                                   current_app.config['QINIU_SECRET_KEY'],
                                   current_app.config['QINIU_BUCKET_NAME'],
                                   file.filename, file.read())
        if not ret['ret']:
            abort(500, ret['msg'])
    else:
        abort(400, 'not allowed file type.')

    url = f"http://{current_app.config['QINIU_BUCKET_URL']}/{ret['key']}"
    file_type = get_file_type(file_extension)

    sessionFactory = getSessionFactory()
    session = sessionFactory.get_session()

    new_resource = Resources(0, file.filename, file_type, url)
    session.add(new_resource)
    session.commit()
    session.close()

    return jsonify({'msg': 'ok'})
Exemplo n.º 29
0
    def put(self, recipe_id):
        # print(request.files)
        file = request.files.get("cover")
        if not file:
            return {"message": "Not a valid image"}, HTTPStatus.BAD_REQUEST
        if not allowed_file(file.filename):
            return {
                "message": "File type not allowed."
            }, HTTPStatus.BAD_REQUEST
        recipe = Recipe.get_by_id(recipe_id=recipe_id)
        if recipe is None:
            return {"message": "Recipe not found"}, HTTPStatus.NOT_FOUND
        current_user = get_jwt_identity()
        if current_user != recipe.user_id:
            return {"message": "Access is not allowed"}, HTTPStatus.FORBIDDEN

        if recipe.cover_image:
            cover_path = os.path.join(os.environ.get("UPLOAD_RECIPES_FOLDER"),
                                      recipe.cover_image)

            if os.path.exists(cover_path):
                os.remove(cover_path)
        filename = save_image(image=file, folder="recipes")
        recipe.cover_image = filename
        recipe.save()
        clear_cache("/recipes")
        return recipe_cover_schema.dump(recipe), HTTPStatus.OK
Exemplo n.º 30
0
def post_upload():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        savename = get_save_name(filename)
        filepath = os.path.join(app.config.get('UPLOAD_DIR'), savename)
        file.save(filepath)
        staticfilepath = filepath[1:].replace("\\", "/")
        bobj = {"filename": filename, "url": staticfilepath, "error": False}

        if os.path.exists(
                os.path.join(app.config.get('CONTENT_DIR'), "uploads.json")):
            fd = open(
                os.path.join(app.config.get('CONTENT_DIR'), "uploads.json"),
                "r")
            _s = fd.read()
            fd.close()
            _os = json.loads(_s)
        else:
            _os = {}

        _os[savename] = filename
        _s = json.dumps(_os)
        fd = open(os.path.join(app.config.get('CONTENT_DIR'), "uploads.json"),
                  "w")
        fd.write(_s)
        fd.close()

    else:
        bobj = {'error': True}

    if not bobj['error']:
        save_uploadfile_to_backup(filepath)
    return json.dumps(bobj)
Exemplo n.º 31
0
Arquivo: app.py Projeto: Elenw/zwiki
def post_upload():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        savename = get_save_name(filename)
        filepath = os.path.join(app.config.get('UPLOAD_DIR'), savename)
        file.save(filepath)
        staticfilepath = filepath[1:].replace("\\", "/")
        bobj = {"filename":filename, "url":staticfilepath, "error": False}

        if os.path.exists(os.path.join(app.config.get('CONTENT_DIR'), "uploads.json")):
            fd = open(os.path.join(app.config.get('CONTENT_DIR'), "uploads.json"), "r")
            _s = fd.read()
            fd.close()
            _os = json.loads(_s)
        else:
            _os = {}

        _os[savename] = filename
        _s = json.dumps(_os)
        fd = open(os.path.join(app.config.get('CONTENT_DIR'), "uploads.json"), "w")
        fd.write(_s)
        fd.close()

    else:
        bobj =  {'error':True}

    if not bobj['error']:
        save_uploadfile_to_backup(filepath)
    return json.dumps(bobj)
    def upload(self, request):
        # check if the post request has the file part
        if 'file' not in request.files:
            print(f"No file part. Redirecting to {request.url}")
            return request.url

        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            print(f"No file selected. Redirecting to {request.url}")
            return request.url

        if file and allowed_file(file.filename):
            filename_secured = secure_filename(file.filename)

            if not os.path.isdir(
                    os.path.join(self._config['UPLOAD_FOLDER'],
                                 request.form['ticker'])):
                os.mkdir(
                    os.path.join(self._config['UPLOAD_FOLDER'],
                                 request.form['ticker']))

            file.save(
                os.path.join(
                    f"{self._config['UPLOAD_FOLDER']}/{request.form['ticker']}",
                    filename_secured))
            return url_for('process_file',
                           ticker=request.form['ticker'],
                           filename=filename_secured)
def predict_image():
    """Gets an image file via POST request, feeds the image to the FaceNet model, the resulting embedding is then
    sent to be compared with the embeddings database. The image file is not stored.

    An html page is then rendered showing the prediction result.
    """
    if request.method == 'POST':
        if 'file' not in request.files:
            return "No file part"

        file = request.files['file']
        filename = file.filename

        if filename == "":
            return "No selected file"

        if file and allowed_file(filename=filename, allowed_set=allowed_set):
            # Read image file as numpy array of RGB dimension
            img = imread(name=file, mode='RGB')
            # Detect and crop a 160 x 160 image containing a human face in the image file
            img = get_face(img=img,
                           pnet=pnet,
                           rnet=rnet,
                           onet=onet,
                           image_size=image_size)

            # If a human face is detected
            if img is not None:

                embedding = forward_pass(
                    img=img,
                    session=facenet_persistent_session,
                    images_placeholder=images_placeholder,
                    embeddings=embeddings,
                    phase_train_placeholder=phase_train_placeholder,
                    image_size=image_size)

                embedding_dict = load_embeddings()
                if embedding_dict:
                    # Compare euclidean distance between this embedding and the embeddings in 'embeddings/'
                    identity = identify_face(embedding=embedding,
                                             embedding_dict=embedding_dict)
                    return render_template('predict_result.html',
                                           identity=identity)

                else:
                    return render_template(
                        'predict_result.html',
                        identity=
                        "No embedding files detected! Please upload image files for embedding!"
                    )

            else:
                return render_template(
                    'predict_result.html',
                    identity=
                    "Operation was unsuccessful! No human face was detected.")
    else:
        return "POST HTTP method required!"
Exemplo n.º 34
0
def submit_form():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = '%s.py' % str(uuid.uuid4())
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        push_to_queue(settings.FILE_PROCESS_TUBE, filename)

        return jsonify({'filename': filename})
def get_image():
    """Gets an image file via POST request, feeds the image to the FaceNet model then saves both the original image
     and its resulting embedding from the FaceNet model in their designated folders.

        'uploads' folder: for image files
        'embeddings' folder: for embedding numpy files.
    """

    if request.method == 'POST':
        if 'file' not in request.files:
            return render_template("warning.html", status="No 'file' field in POST request!")

        file = request.files['file']
        filename = file.filename

        if filename == "":
            return render_template("warning.html", status="No selected file!")

        if file and allowed_file(filename=filename, allowed_set=allowed_set):
            filename = secure_filename(filename=filename)
            # Read image file as numpy array of RGB dimension
            img = imread(name=file, mode='RGB')
            # Detect and crop a 160 x 160 image containing a human face in the image file
            img = get_face(img=img, pnet=pnet, rnet=rnet, onet=onet, image_size=image_size)

            # If a human face is detected
            if img is not None:

                embedding = forward_pass(
                    img=img,
                    session=facenet_persistent_session,
                    images_placeholder=images_placeholder,
                    embeddings=embeddings,
                    phase_train_placeholder=phase_train_placeholder,
                    image_size=image_size
                )
                # Save cropped face image to 'uploads/' folder
                save_image(img=img, filename=filename, uploads_path=uploads_path)
                # Remove file extension from image filename for numpy file storage being based on image filename
                filename = remove_file_extension(filename=filename)
                # Save embedding to 'embeddings/' folder
                save_embedding(embedding=embedding, filename=filename, embeddings_path=embeddings_path)

                return render_template(
                    "upload_result.html",
                    status="Image uploaded and embedded successfully!"
                )

            else:
                return render_template(
                    "upload_result.html",
                    status="Image upload was unsuccessful! No human face was detected!"
                )

    else:
        return render_template("warning.html", status="POST HTTP method required!")
Exemplo n.º 36
0
def autoencoder_api(model_handle="red-car-autoencoder") -> Response:
    """

    autoencoder_api

        This end point is used to encode an image and then get the latentz vector as well as
            the reconstructed image, this kind of technique can be used for image compression
            and video compression, but right now only supports images and specific type of input
            data.
        The latentz vector is a unique representation of the input, and thus the latentz given
            to a encoder and reconstruct the image exactly, thus reducing the data transmitted.

    Args:
        model_handle:  the model handle string, must be in the MODEL_REGISTER

    Returns:
        Response: The response is a JSON containing the reconstructed image and the latent z
            vector for the image

    """
    if model_handle not in MODEL_REGISTER:
        return make_response(
            jsonify(
                {"error": f"{model_handle} not found in registered models"}),
            404)

    if (model_handle in MODEL_REGISTER and
            MODEL_REGISTER[model_handle]["type"] != "variational-autoencoder"):
        return make_response(
            jsonify({"error": f"{model_handle} model is not an AutoEncoder"}),
            412)

    if "file" not in request.files:
        return make_response(jsonify({"error": "No file part"}), 412)

    file: FileStorage = request.files["file"]

    if file.filename == "":
        return make_response(jsonify({"error": "No file selected"}), 417)

    if allowed_file(file.filename):
        image: Image = file2image(file)
        autoencoder = get_autoencoder(model_handle)
        output: Image
        latent_z: np.ndarray
        output, latent_z = autoencoder(image)

        # convert it to b64 bytes
        b64_image = image2b64(output)
        return make_response(
            jsonify(dict(recon_image=b64_image, latent_z=latent_z.tolist())),
            200)

    else:
        return make_response(
            jsonify({"error": f"{file.mimetype} not allowed"}), 412)
Exemplo n.º 37
0
def upload():
    if not request.files:
        return jsonify({'status': 'missing'})
    try:
        data = request.files['inputCSV']
        session['uploaded_filename'] = secure_filename(data.filename)
        if data and allowed_file(data.filename):
            return jsonify_csv(data)
    except Exception:
        print sys.exc_info()[0]
        return jsonify({'status': 'failed', 'message': 'Something went wrong trying to parse your csv file.'})
Exemplo n.º 38
0
def upload_file():
    file = request.files.get('file')
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOADED_FILES_DEST'], filename))
        web_path = os.path.join(app.config['SAVE_PATH'], filename)
        if process_mp3_song(web_path) == 'ok':
            return Response('ok')
        else:
            return Response('song saved but no tags found. chords or lyrics will not be available')
    else:
        return Response('not a valid filetype')
Exemplo n.º 39
0
def import_csv():
    """
    Import data from csv file.
    Securely save csv file. Insert or update entries in database. Delete the
    uploaded file afterwards.
    """
    if request.method == 'POST':
        uploaded_file = request.files['file']
        if not (uploaded_file and allowed_file(uploaded_file.filename)):
            raise InvalidUsage('No file uploaded', status_code=400)
        import_csv_data_in_db(uploaded_file)
        return ('', 200)
    return render_template('import.html')
Exemplo n.º 40
0
def add_spell():
    if not session[GUEST_NAME] or session[GUEST_NAME] != 'root':
        return "Access denied"

    f = request.files['image_name']
    if f and allowed_file(f.filename):
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
        arr_letter = request.form[KEY_ARR_LETTER]
        answer = request.form[KEY_ANSWER]
        level = request.form[KEY_LEVEL]

        if create_spell_entry(f.filename, list(arr_letter), answer, level):
            return render_template('spell_admin.html', msg='Successfully saved')
    return render_template('spell_admin.html', err='Failed to add entry')
Exemplo n.º 41
0
    def post(self):
        # Receive the picture file from the post.
        # Upload the picture to the S3 connection.
        # Retrieve the file name that S3 used to save the picture.
        # Store the file name in the picture entity, with the user_id and pet_id so
        # that pictures can be looked up by either.

        # Get the current user
        user = g.user

        # Check to make sure user owns pet_id
        pet_id = request.form['pet_id']
        pet = Pet.query.filter_by(id=pet_id).first()

        if not pet:
            abort(404, message="Pet not found")
        if pet.user_id != user.id:
            abort(401, message="User does not own pet")

        c = S3Connection(app.config['AWS_ACCESS_KEY'], app.config['AWS_SECRET_KEY'])
        b = c.get_bucket(app.config['AWS_IMAGE_BUCKET'])

        image_file = request.files['pet_image']

        if image_file and allowed_file(image_file.filename):
            filename = secure_filename(image_file.filename)

            # Create new Picture record
            unique_name = get_picture_uuid(filename)
            pic = Picture(unique_name, pet, user)

            # Create key and object on S3
            k = Key(b)
            k.key = unique_name
            k.set_metadata('Content-Type', "image/jpeg")
            k.set_contents_from_file(image_file)
        else:
            abort(400, message="Picture not accepted")

        if pic:
            db_session.add(pic)
            db_session.commit()

        return jsonify(pic.serialize)
Exemplo n.º 42
0
def create_item():
    
    new_game= Game()
    new_game.general_data = request.json["general_data"]
    new_game.character_data = request.json["character_data"]
    new_game.phases = request.json["phases"]

    file = request.files["upload_img"]
    if file and allowed_file(file.filename):
        filename = "{}-{}".format(uuid.uuid4(), secure_filename(file.filename))
        print(filename)
        uploads_route = "{}/app/static/{}".format(os.getcwd(), current_app.config["UPLOAD_FOLDER"] )
        
        file.save(os.path.join(uploads_route, filename))
        new_game.img = filename


    new_game.save()
    return redirect(url_for("main.index"))
Exemplo n.º 43
0
def upload_file():
    file = request.files['file']
    if file and utils.allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return url_for('uploaded_file', filename=filename)
Exemplo n.º 44
0
    def post(self, item_id):
        item = Item.objects.get_or_404(item_id=item_id)

        # only admins or the item submitter can edit the item
        if item.submitter.id != current_user.id:
            if not current_user.is_admin:
                abort(403)

        form = None
        if item.github:
            form = EditGithubItemForm()
        else:
            form = EditItemForm()
            licenses = License.objects.all()
            form.set_licenses(licenses)

        categories = Category.objects.all()
        form.set_categories(categories, g.lang)

        if form.validate_on_submit():
            for title in item.titles:  # ugly, I'll make it shorter, later...
                if title.lang == 'ar':
                    title.title = form.ar_title.data.strip()
                elif title.lang == 'en':
                    title.title = form.en_title.data.strip()
                else:
                    title.title = form.fr_title.data.strip()

            item.tags = form.tags.data.strip().split(',')
            item.category = Category.objects.get(category_id=
                                                 int(form.category.data))

            if form.thumbnail.data:  # if the user has uploaded new thumbnail
                # remove the old one
                item.thumbnail.delete()
                # replace it with the new one
                thumbnail = request.files['thumbnail']
                thumbnail_name = secure_filename(thumbnail.filename)

                if thumbnail and allowed_thumbnails(thumbnail_name):
                    ext = thumbnail.mimetype.split('/')[-1]
                    # use the 'thumbnail' name for all thumbnails
                    filename = '.'.join(["thumbnail", ext])
                    item.thumbnail.put(thumbnail.stream,
                                       content_type=thumbnail.mimetype,
                                       filename=filename)

            if form.blog_post.data.strip():
                item.blog_post = form.blog_post.data
            if not item.github:
                item.description = form.description.data
                item.license = License.objects.get(license_id=
                                                   int(form.license.data))
            else:
                item.github = form.github.data
                item.save()
                # no need to process any uploaded files
                flash('Item updated successfully', category='success')
                return render_template('items/edit_item.html', form=form,
                                       item=item)

        else:
            flash("Couldn't update item", category='error')
            return render_template('items/edit_item.html', form=form,
                                   item=item)

        # now, replace them with the new ones
        uploaded_files = request.files.getlist("files")
        new_files = []
        for file in uploaded_files:
            # Make the filename safe, remove unsupported chars
            filename = secure_filename(file.filename)
            # Check if the file is one of the allowed types/extensions
            if file and allowed_file(filename):
                # put the file in the ListField.
                # see https://gist.github.com/tfausak/1299339
                file_ = GridFSProxy()
                file_.put(file.stream,
                          content_type=file.mimetype,
                          filename=filename)
                new_files.append(file_)
        if len(new_files) > 0:
            # delete old files first
            for file in item.files:
                file.delete()
            # push the new one
            item.files = new_files

        # Save the thing
        item.save()
        flash('Item updated successfully', category='success')
        return render_template('items/edit_item.html', form=form,
                               item=item)
Exemplo n.º 45
0
    def post(self):

        form = AddItemForm()
        item = Item()

        categories = Category.objects.all()
        licenses = License.objects.all()
        form.set_categories(categories, g.lang)
        form.set_licenses(licenses)

        if form.validate_on_submit():
            # first, the user has to share something !
            if not form.github.data and not form.files.data:
                flash('Neither a repo URL nor files has been shared, come on!',
                      category='alert')
                return render_template('items/add_item.html', form=form)

            # give that something at least one title
            if not form.ar_title.data and not form.fr_title.data and \
               not form.en_title.data:

                flash('You need to give this item at least one title, \
                       just pick one language and name it!',
                      category='alert')
                return render_template('items/add_item.html', form=form)

            # now we can proceed
            ar_title = Title()
            fr_title = Title()
            en_title = Title()

            ar_title.title = form.ar_title.data.strip()
            ar_title.lang = 'ar'

            fr_title.title = form.fr_title.data.strip()
            fr_title.lang = 'fr'

            en_title.title = form.en_title.data.strip()
            en_title.lang = 'en'

            item.titles.append(ar_title)
            item.titles.append(fr_title)
            item.titles.append(en_title)

            item.description = form.description.data
            item.tags = form.tags.data.strip().split(',')
            item.category = Category.objects.get(category_id=
                                                 int(form.category.data))

            item.submitter = User.objects.get(id=current_user.id)

            thumbnail = request.files['thumbnail']
            thumbnail_name = secure_filename(thumbnail.filename)

            if thumbnail and allowed_thumbnails(thumbnail_name):
                ext = thumbnail.mimetype.split('/')[-1]
                # use the 'thumbnail' name for all thumbnails
                filename = '.'.join(["thumbnail", ext])
                item.thumbnail.put(thumbnail.stream,
                                   content_type=thumbnail.mimetype,
                                   filename=filename)

            if form.github.data:
                item.github = form.github.data
                item.save()
                # no need to process any uploaded files
                flash('Item submitted successfully', category='success')
                return redirect(url_for('items.detail', item_id=item.item_id))
            else:
                item.license = License.objects.get(license_id=
                                                   int(form.license.data))

        else:
            flash('upload unsuccessful', category='error')
            return render_template('items/add_item.html', form=form)

        uploaded_files = request.files.getlist("files")
        for file in uploaded_files:
            # Make the filename safe, remove unsupported chars
            filename = secure_filename(file.filename)
            # Check if the file is one of the allowed types/extensions
            if file and allowed_file(filename):
                # put the file in the ListField.
                # see https://gist.github.com/tfausak/1299339
                file_ = GridFSProxy()
                file_.put(file.stream,
                          content_type=file.mimetype,
                          filename=filename)
                item.files.append(file_)
        # Save the thing
        item.save()
        flash('Item uploaded successfully', category='success')
        return redirect(url_for('items.detail', item_id=item.item_id))
Exemplo n.º 46
0
def update_settings(settings_type):
    if request.method == "GET":
        html_file = "settings_" + settings_type + ".html"
        days = [];
        classes = [];
        subjects = [];
        print session
        if session["type"] == "tutor":
            for k in session['days'].keys():
                print k
                for x in session['days'][k]:
                    days.append(x);
            classes = session["courses"]
            subjects = session["subjects"]

        
                
        print days
        session['jdays']=json.dumps(days)
        session['jclasses'] = json.dumps(classes)
        session['jsubjects'] = json.dumps(subjects)
        return render_template(html_file,days=json.loads(session['jdays']),dicts=days,classes=json.loads(session['jclasses']), subjects=json.loads(session['jsubjects']))
    if request.method == "POST":
        if request.form["s"] == "Log Out":
            return logout()
        if request.form["s"] == "Update Profile":
            new_account = {}
            old_email = session["email"]
            for key in request.form.keys():
                new_account[key] = request.form[key]
                session[key] = request.form[key]
            if session["type"] == "tutor":
                update_tutor(old_email, new_account, db)
            elif session["type"] == "tutee":
                update_tutee(old_email, new_account, db)
            flash("You have succesfully updated your settings")
            return redirect(url_for("homepage"))
        if request.form["s"] == "Update Times":
            print request.form

            days = create_days(request.form)
            print days
            new_account = {}
            new_account['days'] = days
            new_account['complete'] = 1
            for k in days.keys():
                new_account[k] = True
            update_tutor(session["email"], new_account, db)
            session['days'] = days
            session['complete'] = 1

            return redirect(url_for("update_settings", settings_type="times"))

        if request.form["s"] == "Update Classes":
            courses = request.form.getlist("course")
            subs = request.form.getlist("subject")
            new_account = {}
            new_account['courses'] = courses
            new_account['subjects'] = subs
            for s in subs:
                new_account[s] = True
                session[s] = True
            session['courses'] = courses
            session['subjects'] = subs
            update_tutor(session['email'],new_account,db)
            return redirect(url_for("update_settings", settings_type="classes"))
                         
            
        if request.form["s"] == "Update Profile Picture":
            file = request.files['file']
            if file and allowed_file(file.filename): #check extension
                filename = secure_filename(file.filename)
                y = file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                url = url_for('uploaded_file', filename=filename)
                src = tempfile.gettempdir() + '/' + filename #tempfile.gettempdir() is flask's temporary storage directory

                img_storage = 'static/img/profile_pics/%s_%s' %(session['username'], filename)
                open(session["pic_id"][1:],"w").close() #close the current profile picture's file
                with open(img_storage, 'wb') as f:
                    shutil.copyfile(src, img_storage) #store the file in the Tutee system

                update_dict = {"pic_id":'../%s' % img_storage}
                if session["type"]=="tutee":
                    update_tutee(session["email"], update_dict, db)
                    u = find_user(session["username"], db)
                    session["pic_id"] = u["pic_id"]
                else:
                    update_tutor(session["email"], update_dict, db)
                    u = find_user(session["username"], db)
                    session["pic_id"] = u["pic_id"]
                return redirect("homepage")

            else: #invalid file name
                return redirect("settings/profile")
Exemplo n.º 47
0
def upload():
    data = request.files['inputCSV']
    session['uploaded_filename'] = secure_filename(data.filename)
    if data and allowed_file(data.filename):
        return jsonify_csv(data)
Exemplo n.º 48
0
    def post(self):

        form = AddItemForm()
        item = Item()

        if form.validate_on_submit():
            ar_meta = Meta()
            fr_meta = Meta()
            en_meta = Meta()

            ar_meta.title = form.ar_title.data.strip()
            ar_meta.short_description = form.ar_short_description.data
            ar_meta.lang = 'ar'

            fr_meta.title = form.fr_title.data.strip()
            fr_meta.short_description = form.fr_short_description.data
            fr_meta.lang = 'fr'

            en_meta.title = form.en_title.data.strip()
            en_meta.short_description = form.en_short_description.data
            en_meta.lang = 'en'

            item.meta_info.append(ar_meta)
            item.meta_info.append(fr_meta)
            item.meta_info.append(en_meta)

            item.description = form.description.data

            item.submitter = User.objects.get(id=current_user.id)

        else:
            flash('upload unsuccesful', 'error')
            return render_template('items/add_item.html', form=form)

        uploaded_files = request.files.getlist("files")
        thumbnail = request.files['thumbnail']
        thumbnail_name = secure_filename(thumbnail.filename)

        path = os.path.join(app.config['UPLOAD_FOLDER'], str(item.item_id))
        make_dir(path)

        if thumbnail and allowed_file(thumbnail.filename):
            thumbnail.save(os.path.join(path, thumbnail_name))

        filenames = []
        for file in uploaded_files:
            # Check if the file is one of the allowed types/extensions
            if file and allowed_file(file.filename):
                # Make the filename safe, remove unsupported chars
                filename = secure_filename(file.filename)
                # Move the file form the temporal folder to the upload
                # folder we setup
                file.save(os.path.join(path, filename))
                # Save the filename into a list, we'll use it later
                # filenames.append(filename)
                item.item_data.append(filename)
                # Redirect the user to the uploaded_file route, which
                # will basicaly show on the browser the uploaded file
        # Load an html page with a link to each uploaded file
        # item.item_data.append(filenames)
        item.save()
        flash('upload succesful')
        return render_template('items/add_item.html', form=form)
Exemplo n.º 49
0
 def validate_avatar_file(form, field):
     if field.data and not allowed_file(field.data.filename):
         raise ValidationError("Please upload files with extensions: %s" %
                               "/".join(ALLOWED_AVATAR_EXTENSIONS))
Exemplo n.º 50
0
def upload():
    data = request.files['inputCSV']
    if data and allowed_file(data.filename):
        return jsonify_csv(data)