首页 > 解决方案 > TypeError: Decimal('0.00') 在石墨烯突变对象响应上不是 JSON 可序列化的

问题描述

该应用程序建立在Flask我目前正在开发用户重置密码功能的基础之上。这被定义为客户端发布请求的突变。

客户端将提供其验证密码,然后向他发送一封电子邮件,突变将返回一个UserField标量类型。

此外,我正在使用marshmallow库来序列化数据。

模型.py

class User(db.model):
    __tablename__ = 'users'

    name = db.Column(db.Boolean)
    email = db.Column(db.Unicode, unique=True, nullable=False)
    credit_account = db.Column(db.Numeric(precision=12, scale=2), default=0)

序列化程序.py

class UserSerializer(Schema):
    name = fields.String()
    email = fields.String()
    credit_account = fields.Decimal() # Decimal types here!!!

注意:UserSerializer 上有一个 Decimal 字段,这是 graphql 上的根本问题


下面的代码是GraphQLMutation 的实现。我们使用graphenepython库。

字段.py


class UserField(Scalar):

    @staticmethod
    def serialize(user):
        json = UserSerializer()
        return json.dump(user).data

    @staticmethod
    def parse_literal(node):
        pass

    @staticmethod
    def parse_value(value):
        pass

突变.py

class ResetUserPassword(graphene.Mutation):
    user = graphene.Field(UserField)

    def mutate(self, info, password):
        user = get_user(password=password)
        send_email(user=user,email=user.email, template='reset_password_template') 
        return ResetUserPassword(user=user)

用法:

{
    "query": "mutation { resetPassword(password: \"foobar\") { user }}"
}

现在,我在控制台上收到了这个 TypeError :

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Decimal('0.00') is not JSON serializable

标签: pythongraphqlgraphene-python

解决方案


推荐阅读