-1

I am trying to test this code with postman but I get: TypeError: Object of type 'File' is not JSON serializable.

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'upload.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
class File(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(80), unique=True)
    version = db.Column(db.Integer, unique=True)
    def __init__(self, filename, version):
        self.filename = filename
        self.version = version
class FileSchema(ma.Schema):
    class Meta:
        # Fields to expose
        fields = ('filename', 'version')
file_schema = FileSchema()
files_schema = FileSchema(many=True)
# endpoint to create new file
@app.route("/upload", methods=["POST"])
def add_file():
    filename = request.json['filename']
    version = request.json['version']
    new_file = File(filename, version)
    db.session.add(new_file)
    db.session.commit()
    return jsonify(new_file)
if __name__ == '__main__':
    app.run(debug=True)
davidism
  • 121,510
  • 29
  • 395
  • 339
Dhia Ben Rajeb
  • 13
  • 1
  • 1
  • 5

1 Answers1

0

A file can be downloaded as attachment and not as json.

from flask import send_file

@app.route('/download')
def downloadFile ():
    return send_file(path, as_attachment=True)
Sharan Arumugam
  • 353
  • 6
  • 12