【问题标题】:get unhashable type dict error when using flask-mongoengine and flask-marshmallow使用 flask-mongoengine 和 flask-marshmallow 时出现不可散列的类型 dict 错误
【发布时间】:2016-01-28 15:11:49
【问题描述】:

我正在使用 flask、flask-mongoengine 和 Flask-marshmallow 构建 API。当我尝试使用 marshmallow 返回我的 db 数据时,出现“unhashable type dict”错误。

这是我的模型:

from app import db

class Post(db.Document):
    title = db.StringField(max_length=128)
    body = db.StringField()

这是我的观点:

from flask import jsonify
from app import ma
from app.models import Post

class PostSchema(ma.Schema):
    class Meta:
        fields = ('title', 'body')

post_schema = PostSchema()
posts_schema = PostSchema(many=True)

@mod_post.route('/post/')
def post():
    all_post = Post.objects
    print(all_post)
    result = posts_schema.dump(all_post)
    return jsonify(result)
...

我在这里学习棉花糖教程:http://flask-marshmallow.readthedocs.org/en/latest/

但是,不幸的是发生了错误。有什么建议吗?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    详细的错误信息会有所帮助。从我立即看到的是,您获得了Schema.dump 的结果并将其传递给jsonify(),但结果实际上是转储数据和错误的元组。你应该从这样做开始:

    result, errors = posts_schema.dump(all_posts)
    if errors:
        return jsonify({'error': errors.messages})
    
    return jsonify(result)
    

    然后您可以添加代码来解决转储错误。

    【讨论】:

      【解决方案2】:

      只需更改一个回报: return posts_schema.dump(all_post, many=False)[0], 201

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-24
        • 1970-01-01
        • 1970-01-01
        • 2021-01-10
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多