Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store binary file recieved by Flask into postgres

I currently have a Flask route that reveives file content via POST, and that stores it on the file system, ex:

@app.route('/upload', methods=['POST'])
def upload_file():

    def allowed_file(f):
        return True


    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(upload_dir(), filename))
        return "", 200

I would like to store it in a BYTEA column in postgres, I am not sure how to bind the "data" argument to the insert statement

db.session.execute("""
     INSERT INTO uploaded_file(id, name, type, data) 
     VALUES (:id, :name, :type, %(:data)s)""",
     {"id": str(id),"name": file.filename,"type": "...","data": ???}
like image 398
Max L. Avatar asked Mar 09 '15 22:03

Max L.


1 Answers

The objects in request.files are FileStorage objects. They have the same methods as normal file objects in python.

So, to get the contents of the file as binary, just do this:

data = request.files['file'].read()

Then pass that parameter into the INSERT.

like image 121
Steven Kryskalla Avatar answered Sep 27 '22 21:09

Steven Kryskalla