TypeError:测试Flask API时,“文件”类型的对象不可JSON序列化

时间:2019-03-18 17:31:02

标签: python json flask

我正在尝试与邮递员测试此代码,但得到: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)

1 个答案:

答案 0 :(得分:0)

文件可以下载为附件而不是json。

from flask import send_file

@app.route('/download')
def downloadFile ():
    return send_file(path, as_attachment=True)