【问题标题】:Serialize a dictionary in Python with User defined class as a value (Flask)使用用户定义的类作为值在 Python 中序列化字典(Flask)
【发布时间】:2019-09-26 14:22:34
【问题描述】:

我有一个带有整数键和一个 Person 类作为值的字典。我的 GET by user id 方法有效,但我的 GET UserList 方法无效。

我的 GET UserList 方法正在返回:

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

代码sn-p:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-05-04
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 2019-01-25
      • 2021-07-14
      • 1970-01-01
      • 2010-10-02
      相关资源
      最近更新 更多