I have a very specific question. So i'm writing an app that takes in an integer and a file in flask and stores them as a key value pair in a MongoDB. I was writing the mongo part with the help of a friend that works for mongo and that part of the code was working fine. I want to know now how EXACTLY I'm supposed to send the files i recieve from Flask and put them into the mongoDB.
TLDR. I am writing files to disk, how can i store them inside of the mongoDB using functions that i already know are working, but i myself didn't write?
The tutorial for taking in files i found at http://runnable.com/UiPcaBXaxGNYAAAL/how-to-upload-a-file-to-the-server-in-flask-for-python
The code i'm talking about is hosted on my github https://github.com/DavidAwad/SpaceShare/blob/master/init.py
If you look at line 56. I want to put it into the MongoDB right there, and then remove it from disk, I'm aware however that this is hideously inefficient so if there's a way to make it only write directly in and out of the mongoDB i'm all ears.
The code I'm specifically interested in is this.
# 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.