如何将 Flask 接收到的二进制文件存储到 postgres 中

how to store binary file recieved by Flask into postgres

我目前有一个通过 POST 接收文件内容的 Flask 路由, 并将其存储在文件系统中,例如:

@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

我想将它存储在 postgres 的 BYTEA 列中,我不确定如何将 "data" 参数绑定到插入语句

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

request.files中的对象是FileStorage objects. They have the same methods as normal file objects in python

因此,要以二进制形式获取文件内容,只需执行以下操作:

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

然后将该参数传递给 INSERT