Alex Jones
Alex Jones

Reputation: 21

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:

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. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a File.

    return jsonify(returned_file)

Gets me: TypeError: Object of type File is not JSON serializable

    return send_file(returned_file, attachment_filename="Test.jpg")

Gets me: AttributeError: 'File' object has no attribute 'read'

Upvotes: 1

Views: 1127

Answers (1)

Alex Jones
Alex Jones

Reputation: 21

Aha, I got it! I needed to send it as a buffered stream.

import io
return send_file(io.BytesIO(returned_file.data))

Upvotes: 1

Related Questions