使用Flask,pymongo和GridFS将文件存储到MongoDB中?

时间:2014-12-25 07:28:19

标签: python mongodb flask pymongo gridfs

我有一个非常具体的问题。所以我正在编写一个应用程序,它接受一个整数和一个烧瓶中的文件,并将它们存储为MongoDB中的键值对。我在一个为mongo工作的朋友的帮助下编写了mongo部分,并且部分代码工作正常。我现在想知道我应该如何发送我从Flask收到的文件并将它们放入mongoDB中。

TLDR。我正在将文件写入磁盘,如何使用我已经知道正在工作的函数将它们存储在mongoDB中,但我自己没有写?

接收我在http://runnable.com/UiPcaBXaxGNYAAAL/how-to-upload-a-file-to-the-server-in-flask-for-python

找到的文件的教程

我正在谈论的代码托管在我的github https://github.com/DavidAwad/SpaceShare/blob/master/init.py

如果你看第56行。我想把它放在MongoDB中,然后将它从磁盘中删除,但我知道这是非常低效的,所以如果有办法使它只能直接写入在mongoDB之外我都是耳朵。

我特别感兴趣的代码就是这个。

# put files in mongodb
def put_file(file_location, room_number):
    db_conn = get_db()
    gfs = gridfs.GridFS(db_conn)
    with open(file_location, "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())

... code code code 


    #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(app.config['UPLOAD_FOLDER'],space) #PUT IN MONGODB HERE? IS THIS HOW I DO THAT???
    # 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))
    # maybe redirect user to the uploaded_file route, which will show the uploaded file.

1 个答案:

答案 0 :(得分:0)

请看pymongo(https://flask-pymongo.readthedocs.org/en/latest/),更确切地说是两个函数:send_file和save_file