原创  Flask SQLAlchemy result to json with Marshmallow ( Flask SQLAlchemy 转json 使用Marshmallow )

分类: 2018-06-17T17:15:14    67人阅读   

Marshmallow document url: http://flask-marshmallow.readthedocs.io/en/latest/

使用视屏教程:https://youtu.be/kRNXKzfYrPU

import datetime

from flask import Flask, make_response, redirect, abort, jsonify
import json
import config
from flask_sqlalchemy import SQLAlchemy
import decimal, datetime
from flask_marshmallow import Marshmallow

app = Flask(__name__)
ma = Marshmallow(app)
app.config.from_object(config)
db = SQLAlchemy(app)

class Tt(db.Model):
    __tablename__ = 'tt'
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    title = db.Column(db.String(255))
    content = db.Column(db.String(255))


class TtSchema(ma.Schema):
    class Meta:
        fields = ('id', 'title', 'content')



@app.route('/')
def do_json():
    tt = Tt(title='1111', content='4444')
    db.session.add(tt)
    db.session.commit()
    result = Tt.query.filter(Tt.title == '1111').all()
    tt_schema = TtSchema(many=True)
    return jsonify(tt_schema.dump(result).data)

if __name__ == '__main__':
    app.run(debug=True)
分享到: