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

查看:162
本文介绍了哪种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)

推荐答案

存储二进制数据时,请使用

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()

与其将 data 存储在数据库中,不如将文件存储在文件系统中并将 path 存储到数据库中,通常会更好.

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天全站免登陆