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

标签 python mongodb flask gridfs

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

时我们会得到这个

/uploads/<spacenum>内部我们得到号码并调用 readfile()这会将所需的文件写入 uploads/文件夹。但是我们怎样才能获取该文件并发送它呢?我这样做正确吗?想必我之后需要从磁盘中删除该文件。但我没有file反对像我一样在 upload() 中发送或取消链接功能。

我还有一个问题。我希望 mongodb 在存储这些条目后大约 10 分钟删除它们,我该怎么做。我知道我应该为 gridfs 提供一个特殊的字段,但我只是不知 Prop 体如何做。

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)

关于python - 检索 GridFS 中要从 Flask 发送的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27761674/

相关文章:

python - 从 SPSS 中运行 CMD 行

javascript - Flask 和 JavaScript 删除前确认

javascript - 插入/更新子元素或在集合中插入完整文档 - 取决于现有的主元素

python - 为什么除非我重新启动 Flask 服务器,否则我的列表不会从数据库刷新中填充?

python - 如何从 Flask 中的 HTTP 删除访问正文?

python - 为什么这两个循环的速度完全相同?

python - Jenkins 可以处理 gui/非 gui 交互式 python 或 java 程序吗?

python - 如何避免从 PyPI 更新包?

python - 如何使用默认数据库以外的数据库

node.js - mongoose 模型可以更新 Object Id 字段吗?