在 GridFS 中检索要从 Flask 发送的文件?

retrieving files in GridFS to be sent from Flask?

此代码当前用于从 Flask 应用程序上传文件。用户给了我一个整数和一个文件。然后我将文件存储在 GridFS 中。现在,如果有人试图访问该文件,那么如果他们知道特定的整数,gridfs 需要将其返回给他们。当他们去 URL/uploads/

时我们得到这个

/uploads/<spacenum> 中,我们获取号码并调用 readfile(),这会将所需的文件写入 uploads/ 文件夹。但是我们如何才能获取该文件并发送它呢?我这样做正确吗?据推测,之后我需要从磁盘中删除该文件。但是我没有 file 对象可以像在 upload() 函数中那样发送或取消链接。

我还有一个问题。我希望 mongodb 在我存储这些条目约 10 分钟后删除它们,我该怎么做。我知道我应该给 gridfs 一个特殊的领域我只是不知道如何。

app.config['UPLOAD_FOLDER'] = 'uploads/'
db = "spaceshare"
def get_db(): # get a connection to the db above
    conn = None
    try:
        conn = pymongo.MongoClient()
    except pymongo.errors.ConnectionFailure, e:
       print "Could not connect to MongoDB: %s" % e
       sys.exit(1)
    return conn[db]

# put files in mongodb
def put_file(file_name, room_number):
    db_conn = get_db()
    gfs = gridfs.GridFS(db_conn)
    with open('uploads/' + file_name, "r") as f:
        gfs.put(f, room=room_number)

# read files from mongodb
def read_file(output_location, room_number):
    db_conn = get_db()
    gfs = gridfs.GridFS(db_conn)
    _id = db_conn.fs.files.find_one(dict(room=room_number))['_id']
    #return gfs.get(_id).read()
    with open(output_location, 'w') as f:
        f.write(gfs.get(_id).read())

@app.route('/')
def home():
    return render_template('index.html')


@app.route('/upload',methods=['POST'])
def upload():
    #get the name of the uploaded file
    file=request.files['file']
    #print "requested files"
    space=request.form['space']
    # if the file exists make it secure
    if file and space: #if the file exists
        #make the file same, remove unssopurted chars
        filename=secure_filename(file.filename)
        #move the file to our uploads folder
        file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
        put_file(filename,space)
        # remove the file from disk as we don't need it anymore after database insert.
        os.unlink(os.path.join( app.config['UPLOAD_FOLDER'] , filename))
        # debugging line to write a file
        f = open('debug.txt', 'w')
        f.write('File name is '+filename+' or ' +file.name+' the space is :'+ str(space) )
        return render_template('index.html', filename = filename ,space = space) ##take the file name
    else:
        return render_template('invalid.html')

@app.route('/uploads/<spacenum>', methods=['GET'])
def return_file(spacenum):
    read_file(app.config['UPLOAD_FOLDER'] ,spacenum)
    send_from_directory(app.config['UPLOAD_FOLDER'], filename)
    return render_template('thanks.html' , spacenum = spacenum)

这里是我使用的资源和我构建此代码的示例以及我的完整源代码。预先感谢您的所有帮助!

  1. https://github.com/DavidAwad/SpaceShare
  2. http://runnable.com/UiPcaBXaxGNYAAAL/how-to-upload-a-file-to-the-server-in-flask-for-python
  3. https://api.mongodb.org/python/current/examples/gridfs.html

显然我遇到的问题与文件路径有关。无论如何,这是解决该问题的方法。使用字符串表示形式作为文件名。

# read files from mongodb
def read_file(output_location, room_number):
    db_conn = get_db()
    gfs = gridfs.GridFS(db_conn)
    _id = db_conn.fs.files.find_one(dict(room=room_number))['_id']
    with open(output_location + str(room_number) , 'w') as f:
        f.write(gfs.get(_id).read())
    return gfs.get(_id).read()


@app.route('/upload/<spacenum>', methods=['GET'])
def download(spacenum):
    unSecurefilename = read_file(app.config['UPLOAD_FOLDER'] ,spacenum)
    return send_from_directory(app.config['UPLOAD_FOLDER'], str(spacenum)  )
    #return render_template('index.html' , spacenum = spacenum)