2014-12-25 1 views
0

매우 구체적인 질문이 있습니다. 그래서 저는 술병에서 정수와 파일을 가져 와서 MongoDB의 키 값 쌍으로 저장하는 앱을 작성하고 있습니다. 나는 mongo를 위해 일하는 친구의 도움으로 몽고 파트를 쓰고 있었고 그 코드의 일부는 잘 작동했다. 나는 정확히 내가 플라스크로부터받은 파일을 어떻게 mongoDB에 넣어야하는지 정확히 알고 싶다.Flask, pymongo 및 GridFS를 사용하여 MongoDB에 파일을 저장 하시겠습니까?

TLDR. 내가 디스크에 파일을 쓰고 있는데, 내가 이미 알고있는 기능을 사용하여 mongoDB 안에 저장할 수는 있겠지만, 나는 쓰지 않았다.

당신이 라인 (56)을 보면 내가 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

나는 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. 

답변

관련 문제