簡體   English   中英

使用Flask,pymongo和GridFS將文件存儲到MongoDB中?

[英]Storing files into MongoDB as using Flask, pymongo and GridFS?

我有一個非常具體的問題。 因此,我正在編寫一個應用程序,該應用程序將一個整數和一個文件保存在flask中,並將它們作為鍵值對存儲在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.

查看pymongo( https://flask-pymongo.readthedocs.org/en/latest/ ),更確切地講兩個函數:send_file和save_file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM