Пример #1
0
def delete():
    key = request.form['key']

    my_bucket = get_bucket()
    my_bucket.Object(key).delete()

    flash('Fichier supprimé avec succès')
    return redirect(url_for('files'))
Пример #2
0
def upload():
    file = request.files['file']

    my_bucket = get_bucket()
    my_bucket.Object(file.filename).put(Body=file)

    flash('Fichier téléchargé avec succès')

    return redirect(url_for('files'))
Пример #3
0
def upload():
    file = request.files['file']
    if (file.filename == ''):
        flash('No file selected')
    if (file):
        my_bucket = get_bucket()
        my_bucket.Object(file.filename).put(Body=file)
        flash('File uploaded successfully')
    return redirect(url_for('files'))
Пример #4
0
def download():
    key = request.form['key']
    my_bucket = get_bucket()

    file_obj = my_bucket.Object(key).get()
    return Response(
        file_obj['Body'].read(),
        mimetype='text/plain',
        headers={"Content-Disposition": "attachment;filename={}".format(key)})
Пример #5
0
def index():
    if request.method == 'POST':
        file = request.files['user_file']
        my_bucket = get_bucket()
        my_bucket.Object(file.filename).put(Body=file)
        flash('File uploaded successfully')
        return redirect(url_for('files'))

    return render_template('index.html')
Пример #6
0
def delete_file():
    try:
        key = request.json['key']
        my_bucket = get_bucket()
        my_bucket.Object(key).delete()
        return json.dumps(
            Response_Message(True, "File deleted sucessfully.").__dict__)
    except Exception as ex:
        return json.dumps(
            Response_Message(False, "Filed to delete the file.").__dict__)
Пример #7
0
def files():
    addToRecipe = request.args.get('addToRecipe')
    my_bucket = get_bucket()
    summaries = my_bucket.objects.all()
    components = normal_db_functions.all_components_names(database_address)
    return render_template('files.html',
                           my_bucket=my_bucket,
                           files=summaries,
                           components=components,
                           atR=addToRecipe)
Пример #8
0
def delete_image():
    """Deletes an image off of S3"""

    key = request.form['key']

    my_bucket = get_bucket()
    my_bucket.Object(key).delete()

    flash(f'Photo deleted successfully!')
    return redirect(url_for('files'))
Пример #9
0
def deleteComponentBucket():
    ver = request.form['ver']
    fileName = request.form['Fname']
    if normal_db_functions.check_duplicate(database_address, fileName, ver):
        url = normal_db_functions.get_URL(database_address, fileName, ver)
        key = url[0][0].split("/")[-1]
        my_bucket = get_bucket()
        my_bucket.Object(key).delete()
        normal_db_functions.delete_component(database_address, fileName, ver)
        flash('File deleted successfully')
    return redirect(url_for('files'))
Пример #10
0
def version():
    component = request.form['component']
    addToRecipe = request.form['atR']
    my_bucket = get_bucket()

    versions = normal_db_functions.lookup(database_address, component)
    return render_template('versions.html',
                           my_bucket=my_bucket,
                           componentName=component,
                           versions=versions,
                           atR=addToRecipe)
Пример #11
0
def victor():
    global msg
    global key

    my_bucket = get_bucket()

    msg = get_queue_elem()
    img_name = "Queue_empty.png" if msg is None else msg.body
    key = img_name
    img_file = my_bucket.Object(img_name)
    img_file.url = get_url(img_file)
    return render_template('victor.html', img_file=img_file)
Пример #12
0
def files():
    my_bucket = get_bucket()
    summaries = my_bucket.objects.all()
    image_urls = list()

    s3 = _get_s3_client()
    for summary in summaries:
        image_urls.append(get_presigned_url(s3, summary.key))

    return render_template('files.html',
                           my_bucket=my_bucket,
                           files=zip(summaries, image_urls))
Пример #13
0
def upload_image():
    """Upload an image to S3"""
    #the dict will contain a key 'file' which is same on input form -- this is a FileStorage object from Werkzeug
    file = request.files['file']

    my_bucket = get_bucket()
    my_bucket.Object(file.filename).put(Body=file)

    # get_presigned_url('file')

    flash(f'Photo uploaded successfully!')
    return redirect(url_for('files'))
Пример #14
0
def upload():
    file = request.files['file']

    my_bucket = get_bucket()
    prefix = session['username'] + '/'
    path = prefix + file.filename
    my_bucket.Object(path).put(Body=file)

    flash(
        'File uploaded successfully. You should receive a summary in your inbox shortly.'
    )

    return redirect(url_for('files'))
Пример #15
0
    def post(self):
        key = request.form['key']

        my_bucket = get_bucket()
        my_bucket.Object(key).delete()

        flash('File deleted successfully')
        event_log = LogModel('delete_event', key)
        try:
            event_log.save_to_db()
        except:
            return {"message": "An error occurred while logging."}, 500
        return redirect(url_for('files'))
Пример #16
0
def create():
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        file = request.files['file']
        filename = secure_filename(file.filename)

        species = request.form['species']
        condition = request.form['condition']
        timept = request.form['timept']

        error = None
        if not title:
            error = 'Title is required.'
        if error is not None:
            flash(error)

        if file:  # if there's a file save it
            # save info in SQL database
            db = get_db()
            db.execute(
                'INSERT INTO post (title, author_id, description, file_name, species, condition, timept)'
                ' VALUES (?, ?, ?, ?, ?, ?, ?)',
                (title, g.user['id'], description, filename, species,
                 condition, timept))
            db.commit()

            postid = str(
                db.execute(
                    'SELECT seq from sqlite_sequence WHERE name = "post"').
                fetchone()['seq'])

            # save file on Amazon S3
            my_bucket = get_bucket()
            my_bucket.Object(file.filename).put(Body=file)
            flash("File uploaded successfully! Entries added to index!")

            # make Whoosh index for file
            bucket = "proteomics-db-test"
            file_df = format_file(get_df(bucket, filename))
            file_dict = make_dict(file_df)
            num_proteins = len(file_df)

            # not a great way to pass condition like this, because any
            # modification to post will not be accepted by Whoosh
            create_index(postid, condition, file_dict, create_schema(),
                         num_proteins)

            return redirect(url_for('posts.index'))

    return render_template('posts/create.html')
Пример #17
0
def index():
    """
    Render index page
    """
    # get bucket summary from bucket
    my_bucket = get_bucket()
    summaries = my_bucket.objects.all()

    # get image labels from lambda function
    res = requests.get("https://0f3kzkdn93.execute-api.us-east-2.amazonaws.com/prod")
    labels = res.json()['body']

    # render files.html
    return render_template('index.html', my_bucket=my_bucket, files=summaries, labels=labels)
Пример #18
0
def delete():
    """
    Delete image
    """
    # get key from hidden value
    key = request.form['key']

    # delete file in bucket using key
    my_bucket = get_bucket()
    my_bucket.Object(key).delete()

    # flash message
    flash('File deleted successfully')

    return redirect(url_for('index'))
Пример #19
0
def download():
    key = request.form['key']
    if('.enc' in key):
        source = os.path.join(app_root,'uploads')
        loc0 = os.path.join(source,key[:-4])
        return send_file(loc0, as_attachment=True)
    elif('.enc' not in key):
        my_bucket = get_bucket()
        file_obj = my_bucket.Object(key).get()
        
        return Response(
        file_obj['Body'].read(),
        mimetype='text/plain',
        headers={"Content-Disposition": "attachment;filename={}".format(key)}
    )
Пример #20
0
def download():
    from app import current_user
    user = User.query.get_or_404(current_user.id)
    key = request.form['key']
    if('.enc' == key[-4:]):
        user.download = key
        db.session.commit()
        return redirect(url_for('auth.download1'))
    elif('.enc' != key[-4:]):
        my_bucket = get_bucket()
        file_obj = my_bucket.Object(key).get()
        return Response(
        file_obj['Body'].read(),
        mimetype='text/plain',
        headers={"Content-Disposition": "attachment;filename={}".format(key)}
    )
Пример #21
0
def upload():
    file = request.files['file']
    max_size = 640, 480

    in_mem_file = BytesIO()

    img = Image.open(file)
    img.thumbnail(max_size, Image.ANTIALIAS)
    img.save(in_mem_file, format=img.format)

    my_bucket = get_bucket()
    my_bucket.Object("folder/" +
                     file.filename).put(Body=in_mem_file.getvalue())

    flash('File uploaded successfully')
    return redirect(url_for('files'))
Пример #22
0
def download():
    """
    Download image
    """
    # get key from hidden value
    key = request.form['key']

    # get file in bucket using key
    my_bucket = get_bucket()
    file_obj = my_bucket.Object(key).get()

    # download file
    return Response(
        file_obj['Body'].read(),
        mimetype='text/plain',
        headers={'content-Disposition': f'attachment;filename={key}'}
    )
Пример #23
0
def all_files():
    my_bucket = get_bucket()
    summaries = my_bucket.objects.all()
    payload = []
    data = {}
    # json.dumps(summaries.__dict__)
    for summary in summaries:
        file = summary.key
        lastmodified = datetimeformat(summary.last_modified)
        filetype = file_type(summary.key)

        data['file'] = file
        data['lastmodified'] = lastmodified
        data['filetype'] = filetype

        payload.append(data)
    return jsonify(payload)
Пример #24
0
def delete(id):
    # remove from SQL database
    get_post(id)
    db = get_db()
    db.execute('DELETE FROM post WHERE id = ?', (id, ))
    db.commit()

    key = request.form['key']
    my_bucket = get_bucket()
    my_bucket.Object(key).delete()

    # remove file contents from Whoosh index
    remove_doc(str(id))

    flash('File deleted successfully! Contents removed from index!')

    return redirect(url_for('posts.index'))
Пример #25
0
    def post(self):
        key = request.form['key']

        my_bucket = get_bucket()
        file_obj = my_bucket.Object(key).get()
        event_log = LogModel('download_event', key)
        try:
            event_log.save_to_db()
        except:
            return {"message": "An error occurred while logging."}, 500

        return Response(file_obj['Body'].read(),
                        mimetype='text/plain',
                        headers={
                            "Content-Disposition":
                            "attachment;filename={}".format(key)
                        })
Пример #26
0
    def post(self):
        file = request.files['file']
        files_list = get_all_objects_from_bucket()
        if file.filename in files_list:
            flash('File upload cannot happen due to duplicate file name')
            return redirect(url_for('files'))

        my_bucket = get_bucket()
        my_bucket.Object(file.filename).put(Body=file)

        flash('File uploaded successfully')

        event_log = LogModel('upload_event', file.filename)
        try:
            event_log.save_to_db()
        except:
            return {"message": "An error occurred while logging."}, 500

        return redirect(url_for('files'))
Пример #27
0
def getDogBreedFromUrl(id):
    print(id)

    url = 'https://s3.amazonaws.com/' + S3_BUCKET + '/' + id
    params = {'imagePath': url}
    print(params)

    #apiUrl = 'http://0.0.0.0:8080/getDogBreed'
    apiUrl = 'http://172.104.212.211:8000/getDogBreed'

    r = requests.post(url=apiUrl, params=params)
    data = r.json()
    print(data)

    my_bucket = get_bucket()
    add_tags_to_object(id, url, data['type'], data['breed'])
    objects = get_detail_bucket_list()

    return render_template('files.html', my_bucket=my_bucket, files=objects)
Пример #28
0
def retrieve():
    ver = request.args.get('ver')
    fileName = request.args.get('Fname')

    connection = normal_db_functions.create_connection(database_address)
    if normal_db_functions.check_duplicate(database_address, fileName, ver):
        url = normal_db_functions.get_URL(database_address, fileName, ver)
        key = url[0][0].split("/")[-1]
        print(key)
        my_bucket = get_bucket()
        file_obj = my_bucket.Object(key).get()

        return Response(file_obj['Body'].read(),
                        mimetype='text/plain',
                        headers={
                            "Content-Disposition":
                            "attachment;filename={}".format(key)
                        })
    else:
        return jsonify("DOESN'T EXIST"), 404
Пример #29
0
def enc_upload():
    from app import current_user
    user = User.query.get_or_404(current_user.id)
    source = os.path.join(app_root, 'uploads')
    if (not os.path.exists(source)):
        os.makedirs(source)
    target = os.path.join(app_root, 'encrypted')
    if (not os.path.exists(target)):
        os.makedirs(target)
    file = request.files['file']
    if (file.filename == ''):
        flash('No file selected')
    if (file):
        loc0 = os.path.join(source, file.filename)
        file.save(loc0)
        loc = os.path.join(target, file.filename + ".enc")
        with open(loc0, 'rb') as fo:
            plaintext = fo.read()
        res = ''.join(
            random.choices(string.ascii_uppercase + string.digits, k=20))
        res1 = bytes(res, 'utf-8')
        key = hashlib.sha256(res1).digest()
        enc = encrypt(plaintext, key)
        with open(loc, 'wb') as fo:
            fo.write(enc)
        my_bucket = get_bucket()
        my_bucket.Object(file.filename + ".enc").put(Body=open(loc, 'rb'))
        source1 = os.path.join(app_root, 'keys')
        if (not os.path.exists(source1)):
            os.makedirs(source1)
        source2 = os.path.join(source1, file.filename + ".enc key.txt")
        keydir = eval(user.keydir)
        keydir[file.filename + ".enc"] = key
        user.keydir = str(keydir)
        db.session.commit()
        with open(source2, "w") as file1:
            file1.write(res)
        file1.close()
        flash('File uploaded successfully')
        return send_file(source2, as_attachment=True)
    return redirect(url_for('files'))
Пример #30
0
def upload():
    """
    Upload image
    """
    try:
        file = request.files['file']
    except:
        pass
    else:
        # check file extension
        if validate_extension(file.filename):
            # upload user file to bucket
            my_bucket = get_bucket()
            my_bucket.Object(file.filename).put(Body=file)

            # flash message
            flash('File uploaded successfully')
        else:
            flash('Only .jpg, .jpeg and .png are allowed')
    finally:
        return redirect(url_for('index'))