[英]How to return a file in flask from sqlalchemy database
I'm trying to create an app that will let me store files on a database and retrieve them (I know in most cases it's better not to store files on the database itself, but in this instance, that's not what I want to do).我正在尝试创建一个应用程序,让我将文件存储在数据库中并检索它们(我知道在大多数情况下最好不要将文件存储在数据库本身上,但在这种情况下,这不是我想要做的) . I can get the file (a jpg image) stored in the database with:我可以通过以下方式获取存储在数据库中的文件(jpg 图像):
class File(db.Model):
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.LargeBinary, nullable=False)
def __init__(self, data):
self.data = data
@app.route("/file/add", methods=["POST"])
def add_file():
data = request.files.get("data")
record = File(data.read())
db.session.add(record)
db.session.commit()
Now how do I return the file?现在如何返回文件?
@app.route("/file/get", methods=["GET"])
def get_file():
returned_file = db.session.query(File.data).first()
return # What goes here?
Some things I've tried (Many of which I didn't expect to work, but I think the error messages are helpful):我尝试过的一些事情(其中许多我没想到会起作用,但我认为错误消息很有帮助):
return returned_files
Gets me: TypeError: The view function did not return a valid response.得到我:TypeError:视图 function 没有返回有效响应。 The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a File.返回类型必须是字符串、字典、元组、响应实例或可调用的 WSGI,但它是文件。
return jsonify(returned_file)
Gets me: TypeError: Object of type File is not JSON serializable得到我: TypeError: Object 文件类型不是 JSON 可序列化
return send_file(returned_file, attachment_filename="Test.jpg")
Gets me: AttributeError: 'File' object has no attribute 'read'得到我: AttributeError: 'File' object has no attribute 'read'
Aha, I got it.啊哈,我明白了。 I needed to send it as a buffered stream.我需要将它作为缓冲流发送。
import io
return send_file(io.BytesIO(returned_file.data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.