二进制数据应该使用哪种 SQLAlchemy 列类型? [英] Which SQLAlchemy column type should be used for binary data?

查看:40
本文介绍了二进制数据应该使用哪种 SQLAlchemy 列类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的数据库中存储音频文件.例如,我知道字符串将使用 db.String,整数 db.Integer,但不知道音频数据将使用什么.SQLAlchemy 中使用什么数据类型来存储这种类型的数据?

I want to store audio files in my database. I know, for example, that strings would use db.String, integers db.Integer, but not what audio data would use. What data type is used to store this type of data in SQLAlchemy?

class Audio(db.Model):
    __tablename__ = 'audio'
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    title = db.Column(db.String(64), unique=True)

推荐答案

存储二进制数据时,使用 LargeBinary 类型.尽管它的名字,它适用于任何大小的二进制数据.

When storing binary data, use the LargeBinary type. Despite its name, it is appropriate for any sized binary data.

data = db.Column(db.LargeBinary)

在 Flask 视图中读取上传文件中的数据.

Read the data from the uploaded file in your Flask view.

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

与将数据存储在数据库中相比,通常最好将文件存储在文件系统中,并将文件的路径存储在数据库中.

Rather than storing the data in the database, it's typically better to store files in the filesystem, and store the path to the file in the database.

由于您大概是在提供这些文件,而不仅仅是存储它们,因此从文件系统提供文件的效率要高得多.有关从数据库提供数据的更多讨论,请参阅此答案.

Since you're presumably serving these files, not just storing them, it is much more efficient to serve the files from the filesystem. See this answer for more discussion on serving data from the database.

这篇关于二进制数据应该使用哪种 SQLAlchemy 列类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆