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

时间:2015-01-04 02:09:51

标签: python mongodb flask gridfs

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

时会收到此信息

/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

1 个答案:

答案 0 :(得分:0)

显然我遇到的问题与文件路径有关。无论如何这里是解决这个问题的方法。使用String表示作为文件名。

# 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)