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

2024-03-14

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

@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 are 文件存储 http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.FileStorage对象。他们有相同的方法python中的普通文件对象 https://docs.python.org/2/library/stdtypes.html#file-objects.

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

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

然后将该参数传递到INSERT.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐