我正在尝试使用Flask-SQLAlchemy从SQLite读取BLOB(LargeBinary)对象,我收到此错误:TypeError: must be string or read-only buffer, not None
。
我的代码如下:
@app.route('/csv/<int:job_id>', methods=['GET'])
def get_csv(job_id):
""" Action to retrieve the compressed CSV from the database """
job = db.session.query(Job).filter_by(id=job_id).first()
csv = decompress(job.compressed_csv)
sio = StringIO()
sio.write(csv)
sio.seek(0)
return send_file(sio,
attachment_filename=
"{}_{}.txt".format(job_id, time.strftime("%Y%m%d%H%M%S")),
as_attachment=True)
我的SQLAlchemy模型是:
class Job(db.Model):
""" SQLAlchemy Job Model """
id = db.Column(db.Integer, primary_key=True)
list_type_id = db.Column(db.Integer, db.ForeignKey('list_type.id'),
nullable=False)
list_type = db.relationship('ListType',
backref=db.backref('jobs', lazy='dynamic'))
record_count = db.Column(db.Integer, nullable=False)
status = db.Column(db.Integer, nullable=False)
sf_job_id = db.Column(db.Integer, nullable=True)
created_at = db.Column(db.DateTime, nullable=False)
compressed_csv = db.Column(db.LargeBinary)
def __init__(self, list_type_id, record_count=0, status=0, sf_job_id=0,
csv=None, created_at=datetime.utcnow()):
self.list_type_id = list_type_id
self.created_at = created_at
self.record_count = record_count
self.status = status
self.sf_job_id = sf_job_id
self.compressed_csv = csv
def __repr__(self):
return '<Job {}>'.format(self.id)
这是我的架构:
CREATE TABLE alembic_version (
version_num VARCHAR(32) NOT NULL
);
CREATE TABLE job (
id INTEGER NOT NULL,
list_type_id INTEGER NOT NULL,
record_count INTEGER NOT NULL,
status INTEGER NOT NULL,
sf_job_id INTEGER NOT NULL,
created_at DATETIME NOT NULL,
compressed_csv BLOB,
PRIMARY KEY (id),
FOREIGN KEY(list_type_id) REFERENCES list_type (id)
);
CREATE TABLE list_type (
id INTEGER NOT NULL,
name VARCHAR(80) NOT NULL,
PRIMARY KEY (id),
UNIQUE (name)
);
答案 0 :(得分:2)
事实证明我使用csv = buffer(compress(csv))
插入数据。这导致为该字段存储NULL。删除buffer
功能解决了问题。