how to store binary file recieved by Flask into postgres

风格不统一 提交于 2019-12-30 07:17:08

问题


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": ???}

回答1:


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.



来源:https://stackoverflow.com/questions/28952665/how-to-store-binary-file-recieved-by-flask-into-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!