开发者社区> 问答> 正文

flask_restful-TypeError:Record类型的对象不是JSON可序列化的

我尝试在rest api内提供一个自定义对象,该api由flask-restful创建。

对象:记录 import json

class Record():
    #CLASS RECORD
    def __init__(self, DateTime, DateTimeText, Status, Icon, Temp):
        #INITIALIZE
        self.DateTime = DateTime
        self.DateTimeText = DateTimeText
        self.Status = Status
        self.Icon = Icon
        self.Temp = Temp

    def __repr__(self):
        return json.dumps(self, default=lambda o: o.__dict__, sort_keys=False, indent=4)

结果:打印(记录) { "DateTime": 1583949600, "DateTimeText": "2020-03-11 18:00:00", "Status": "Clouds", "Icon": "04n", "Temp": 280.57 } REST API: from flask_restful import Resource, Api, reqparse

class _Weather(Resource):
    #WEATHER
    def get(self):
        #GET WEATHER
        return {'value': Weather.Record}

self.Api.add_resource(_Weather, '/api/weather')

* 错误:

所有其他调用都可以正常工作,只有我自定义对象(http:// localhost:80 / api / weather)返回以下错误堆栈:

File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
    return original_handler(e)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(\*rgs, \*kwargs)))
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
    return original_handler(e)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(\*rgs, \*kwargs)))
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 38, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](\*req.view_args)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 472, in wrapper
    return self.make_response(data, code, headers=headers)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\__init__.py", line 501, in make_response
    resp = self.representations[mediatype](data, \*rgs, \*kwargs)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_restful\representations\json.py", line 21, in output_json
    dumped = dumps(data, \*settings) + "\n"
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 201, in encode
    chunks = list(chunks)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 431, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 438, in _iterencode
    o = _default(o)
  File "C:\Users\Martin\AppData\Local\Programs\Python\Python38-32\Lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Record is not JSON serializable

我尝试了很多不同的方法,这些方法可以在此处找到。这些都不适合我。

Python 3.8.2

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 20:29:16 710 0
1 条回答
写回答
取消 提交回答
  • 您在这里有几个选择。

    1. Make a tojson() method for your Record class and call that for your return value. It will basically just return the underlying ` dict ` for your object.

      def tojson(self): return self.dict

    2. Pass ` Weather.Record.dict ` directly as your return value

    因此,您的return语句将类似于以下之一:

    return {'value':Weather.Record。字典 }`

    或者,使用Flask中的jsonify:

    返回jsonify({ '值':“Weather.Record。字典 })

    或替换Weather.Record。如果您将该方法添加到类中,则使用Weather.Record.tojson()进行dict。

    回答来源:stackoverflow

    2020-03-24 20:29:23
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载