使用用户定义的类作为值在Python中序列化字典(Flask)

时间:2019-05-08 19:23:40

标签: python json python-3.x flask serialization

我有一本带有整数键和Person类作为值的字典。我的按用户ID的GET方法有效,但我的GET UserList的方法无效。

我的GET UserList方法返回:

{
    "name": null,
    "age": 0,
    "address": null,
    "city": null,
    "state": null,
    "zip_code": null
}

代码段:

from flask import Flask, request, abort
from flask_restful import Api, Resource, fields, marshal_with

user_fields = {
    'name':   fields.String,
    'age':    fields.Integer,
    'address': fields.String,
    'city': fields.String,
    'state': fields.String,
    'zip_code': fields.String
}

class User(Resource):
    @staticmethod
    @marshal_with(user_fields)
    def get(path_user_id):
        # Checks to make sure the user exists otherwise throws an error
        if path_user_id not in user_dict:
            abort(400)

        return user_dict.get(path_user_id)

# This one is not working
class UserList(Resource):
    @staticmethod
    @marshal_with(user_fields)
    def get():
        return user_dict.items()

class Person:
    def __init__(self, name, age, address, city, state, zip_code):
        self.name = name
        self.age = age
        self.address = address
        self.city = city
        self.state = state
        self.zip_code = zip_code

1 个答案:

答案 0 :(得分:0)

UserList一样,您正在将user_fields的get方法与User一起编组,因此响应被编组为具有相同的格式。