Flask之 Marshmallow 踩坑实录
1.Marshmallow.ModelSchema 报错
AttributeError: 'Marshmallow' object has no attribute 'ModelSchema'
`from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///marshmallowjson.db'
db = SQLAlchemy(app)
ma = Marshmallow(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
item_name = db.Column(db.String(50))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User', backref='items')
class UserSchema(ma.ModelSchema):
class Meta:
model = User
class ItemSchema(ma.ModelSchema):
class Meta:
model = Item
@app.route('/')
def index():
users = User.query.all()
user_schema = UserSchema(many=True)
output = user_schema.dump(users).data
return jsonify({'user': output})
if name == 'main':
app.run(debug=True)
`
解决: pip install marshmallow-sqlalchemy
原因: 仅安装了烧瓶棉花糖,整个代码保持不变,但需要添加以使用SQLAlchemy。
问题二: flask_marshmallo>=0.12.0,ma.ModelSchema和ma.TableSchema被删除
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(name)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test.db"
db = SQLAlchemy(app)
ma = Marshmallow(app)
flask-marshmallow<0.12.0
class AuthorSchema(ma.ModelSchema):
class Meta:
model = Author
flask-marshmallow>=0.12.0 (recommended)
class AuthorSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Author
load_instance = True
flask-marshmallow>=0.12.0 (not recommended)
from marshmallow_sqlalchemy import ModelSchema
class AuthorSchema(ModelSchema):
class Meta:
model = Author
sql_session = db.session