Reputation: 3058
I have a simple model
that I want to store the binary contents of a PDF file in a data
attribute:
from app import db
class Model(db.Model):
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.PickleType, nullable=True)
I'm trying to add some arbitrary PDF file to the data
attribute as follows:
@app.route('/')
def index() -> str:
model = Model.query.get(1)
model.data = open('./app/static/pdf/file.pdf', 'rb')
db.session.commit()
return ''
But I'm getting the following error:
sqlalchemy.exc.StatementError: (builtins.TypeError) cannot serialize '_io.BufferedReader' object
[SQL: UPDATE model SET data=? WHERE model.id = ?]
[parameters: [{'data': <_io.BufferedReader name='./app/static/pdf/file.pdf'>, 'model_id': 1}]]
What is the correct way of doing this, please? How should I go about serializing a PDF file?
Thanks for any help :-)
Upvotes: 1
Views: 1651
Reputation: 24966
The difference between
model.data = open('./app/static/pdf/file.pdf', 'rb')
and
model.data = open('./app/static/pdf/file.pdf', 'rb').read()
is the difference between to pickling a file handle (which has some unpickle-able parts) and pickling a byte array.
Upvotes: 2