gpt4 book ai didi

python - 'Marshmallow' 对象没有属性 'ModelSchema'

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:09 25 4
gpt4 key购买 nike

文档中的一切看起来都很好,但是当我运行应用程序时它仍然给我这个错误:

  File "main.py", line 21, in <module>
class UserSchema(ma.ModelSchema):
AttributeError: 'Marshmallow' object has no attribute 'ModelSchema'

一切都正确导入。数据库已提交。该行为在 pipenv 和 venv 上是相同的。

我错过了什么吗?

from flask import Flask, jsonify
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)

最佳答案

Conf.py

from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

db = SQLAlchemy(app)
ma = Marshmallow(app)

# flask-marshmallow<0.12.0

class UserSchema(ma.ModelSchema):
class Meta:
model = User

# flask-marshmallow>=0.12.0(推荐)

from conf import ma
class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
load_instance = True

# flask-marshmallow>=0.12.0(不推荐)

from marshmallow_sqlalchemy import ModelSchema
class UserSchema(ModelSchema):
class Meta:
model = User
sql_session = db.session

关于python - 'Marshmallow' 对象没有属性 'ModelSchema',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57984649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com