2014-12-25 214 views
0

我有一個非常具體的問題。所以我正在編寫一個應用程序,它接收一個整數和一個文件在燒瓶中,並將它們作爲關鍵值對存儲在MongoDB中。我在一個爲mongo工作的朋友的幫助下編寫了mongo部分,並且這部分代碼工作正常。我想知道現在我應該如何將我從Flask收到的文件發送到mongoDB中。使用Flask,pymongo和GridFS將文件存儲到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. 

回答

相關問題