1
from flask import Flask, request, abort
from flask_restful import Api, Resource
import jsonpickle

app = Flask(__name__)
api = Api(app)

user_dict = {}
user_id = 0

class User(Resource):
    @staticmethod
    def get(path_user_id):
        if path_user_id not in user_dict:
            abort(400)

        test = jsonpickle.encode(user_dict.get(path_user_id), unpicklable=False)

        return jsonpickle.encode(user_dict.get(path_user_id), unpicklable=False)

    @staticmethod
    def put(path_user_id):
        if path_user_id not in user_dict:
            abort(400)

        update_and_add_user_helper(path_user_id, request.get_json())

    @staticmethod
    def delete(path_user_id):
        if path_user_id not in user_dict:
            abort(400)

        user_dict.pop(path_user_id, None)


class UserList(Resource):
    @staticmethod
    def get():
        return jsonpickle.encode(user_dict, unpicklable=False)

    @staticmethod
    def post():
        global user_id
        user_id = user_id + 1
        update_and_add_user_helper(user_id, request.get_json())


def update_and_add_user_helper(u_id, request_payload):
    name = request_payload["name"]
    age = request_payload["age"]
    address = request_payload["address"]
    city = request_payload["city"]
    state = request_payload["state"]
    zip_code = request_payload["zip"]
    user_dict[u_id] = Person(name, age, address, city, state, zip_code)


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

api.add_resource(User, "/users/<int:path_user_id>")
api.add_resource(UserList, "/users")

if __name__ == "__main__":
    app.run(debug=True)

调试get方法(通过用户ID)后,我得到了这个

test = '{"address": "123 Chestnut Ln", "age": 35, "city": "Denton", "name": "James Smith", "state": "Texas", "zip_code": "76210"}'

但是,正在显示的响应是:"{\"1\": {\"address\": \"123 Chestnut Ln\", \"age\": 35, \"city\": \"Denton\", \"name\": \"James Smith\", \"state\": \"Texas\", \"zip_code\": \"76210\"}}"

Flask 是否在返回时序列化对象?

另外,请假设已完成 POST 请求并且字典中有值。

4

1 回答 1

1

我试图搜索烧瓶文档,但没有成功,所以我试图摆弄你的代码,所以这就是我发现的:

当我改变时:

return jsonpickle.encode(user_dict.get(path_user_id), unpicklable=False)

return user_dict.get(path_user_id)

我有TypeError: Object of type 'Person' is not JSON serializable例外。毕竟,flask 似乎会序列化响应。

于 2019-05-08T17:16:03.617 回答