简体   繁体   English

Flask API TypeError:“响应”类型的对象不是 JSON 可序列化的

[英]Flask API TypeError: Object of type 'Response' is not JSON serializable

i have a problem with Python Flask Restful API and data goes to Elasticsearch, when i post a new data with Postman, problem is:我在使用 Python Flask Restful API 时遇到问题,数据转到 Elasticsearch,当我使用 Postman 发布新数据时,问题是:

TypeError: Object of type 'Response' is not JSON serializable类型错误:“响应”类型的对象不是 JSON 可序列化的

Can you help me?你能帮助我吗?

Model:模型:

   from marshmallow import Schema, fields, validate

class Person(object):
    def __init__(self,tcno=None,firstname=None,lastname=None,email=None,birthday=None,country=None,gender=None):
        self.__tcno = tcno
        self.__firstname = firstname
        self.__lastname = lastname
        self.__email = email
        self.__birthday = birthday
        self.__country = country
        self.__gender = gender

    def __repr__(self):
        return '<Person(firstname={self.__firstname!r})>'.format(self=self)

class PersonSchema(Schema):
    tcno = fields.Str(required=True,validate=[validate.Length(min=11, max=11)])
    firstname = fields.Str(required=True)
    lastname = fields.Str(required=True)
    email = fields.Email(required=True,validate=validate.Email(error="Not a valid email"))
    birthday = fields.Date(required=True)
    country = fields.Str()
    gender = fields.Str()

View:看法:

from flask import Response, json, request, jsonify, Flask
import requests
from flask_marshmallow import Marshmallow
from flask_restful import Api, Resource

from Person import Person, PersonSchema

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

class Apici(Resource):
    def __init__(self):
        pass

    def get(self,people_id):
        url = "http://localhost:9200/people/person/{}".format(people_id)
        headers = {"Content-type": "application/json"}
        r = requests.get(url=url, headers=headers)
        json_data = json.loads(r.text)
        if json_data['found'] is False:
            mesaj = json.dumps({"found": "False"})
            resp = Response(mesaj, status=201, mimetype='application/json')
            return resp
        return json_data["_source"]

    def post(self,people_id):
        json_input = request.get_json()
        person_schema = PersonSchema()
        person, errors = person_schema.load(json_input)
        if errors:
            return jsonify({'errors': errors}), 422
        #result = person_schema(person)
        url = "http://localhost:9200/people/person/{}".format(people_id)
        headers = {"Content-type": "application/json"}
        print(url)

        r = requests.post(url=url, json=json_input, headers=headers)
        print(r)
        json_data = json.loads(r.text)
        if json_data["result"] is "Updated":
            message = json.loads({"result": "updated"})
            resp = Response(message, status=201, mimetype='application/json')
            return resp
        message = json.loads({"result": "created"})
        resp = Response(message, status=201, mimetype='application/json')
        return resp #jsonify(result.data)

    def put(self):
        json_input = request.get_json()
        person_schema = PersonSchema()
        person, errors = person_schema.load(json_input)
        if errors:
            return jsonify({'errors': errors}), 422
        result = person_schema(person)
        url = "http://localhost:9200/people/person/{}".format(request.url[-1])
        headers = {"Content-type": "application/json"}
        r = requests.post(url=url, json=json_input, headers=headers)
        json_data = json.loads(r.text)
        if json_data["result"] is "Updated":
            message = json.dumps({"result": "updated"})
            resp = Response(message, status=201, mimetype='application/json')
            return resp
        message = json.dumps({"result": "created"})
        resp = Response(message, status=201, mimetype='application/json')
        return resp #jsonify(result.data)

    def delete(self):
        url = "http://localhost:9200/people/person/{}".format(request.url[-1])
        headers = {"Content-type": "application/json"}
        r = requests.delete(url=url,headers=headers)
        json_data = json.loads(r.text)
        if json_data["result"] == "not_found":
            message = json.dumps({"result": "not_found"})
            return Response(message, status=201, mimetype='application/json')
        message = json.dumps({"result": "deleted"})
        resp = Response(message, status=201, mimetype='application/json')
        return resp


class ApiciList(Resource):
    def __init__(self):
        pass

    def get(self):
        url = "http://localhost:9200/people/person/_search"
        body = {"query": {"match_all": {}}}
        headers = {"Content-type": "application/json"}
        r = requests.get(url=url, json=body, headers=headers)
        json_data = json.loads(r.text)
        return json_data["hits"]["hits"]


api.add_resource(ApiciList, '/person')
api.add_resource(Apici, '/person/<string:people_id>')


if __name__ == '__main__':
    app.run(port=5010,debug=True)

Error:错误:

127.0.0.1 - - [08/Jun/2017 11:37:18] "POST /person/1 HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.6/dist-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 32, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.6/dist-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 32, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.6/dist-packages/flask_restful/__init__.py", line 481, in wrapper
    return self.make_response(data, code, headers=headers)
  File "/usr/local/lib/python3.6/dist-packages/flask_restful/__init__.py", line 510, in make_response
    resp = self.representations[mediatype](data, *args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/flask_restful/representations/json.py", line 20, in output_json
    dumped = dumps(data, **settings) + "\n"
  File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.6/json/encoder.py", line 201, in encode
    chunks = list(chunks)
  File "/usr/lib/python3.6/json/encoder.py", line 437, in _iterencode
    o = _default(o)
  File "/usr/lib/python3.6/json/encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'Response' is not JSON serializable

EDIT: I found problem.编辑:我发现问题。 It was in def post(self,people_id) method:它在 def post(self,people_id) 方法中:

   if errors:
        return jsonify({'errors': errors}), 422

new line:新队:

if errors:
    message = json.dumps({'errors': errors})
    return Response(message, status=422, mimetype='application/json')

Inspired from this bug , here is a shorter way of doing it:受这个bug 的启发,这里有一个更短的方法:

from flask import jsonify, make_response

def myMethod():
    ....
    return make_response(jsonify(data), 200)

This can be simply done by:这可以通过以下方式简单地完成:

from flask import jsonify
def myMethod():
    ....
    response = jsonify(data)
    response.status_code = 200 # or 400 or whatever
    return response

我有一个类似的问题,问题是我使用了 jsonify 两次( jsonify(jsonify({abc:123}))

def post(self):
    some_json=request.get_json()
    return jsonify({'you sent ':some_json})

enough to solve this issue足以解决这个问题

For this we can try为此我们可以尝试

Step 1 : response=response.json()第 1 步:响应=response.json()

Step 2 : response=json.dumps(response)第 2 步:响应=json.dumps(响应)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flask API 抛出类型错误:Object 类型不是 JSON 可序列化 - Flask API throws TypeError: Object of type is not JSON serializable Python/Flask - “TypeError”类型的对象不是 JSON 可序列化的 - Python/Flask - Object of type "TypeError' is not JSON serializable Python - Flask - TypeError 类型的 Object 不是 JSON 可序列化的 - Python - Flask - Object of type TypeError is not JSON serializable TypeError:Object 类型 Response 不是 JSON 可序列化 (2) - TypeError: Object of type Response is not JSON serializable (2) 调用 Flash restful 服务时在烧瓶上显示错误。 类型错误:“响应”类型的对象不是 JSON 可序列化的 - Error shown on flask when calling Flash restful service. TypeError: Object of type 'Response' is not JSON serializable TypeError: Object of type function is not JSON serializable when using flask_jwt_extended int RESTful API - TypeError: Object of type function is not JSON serializable when using flask_jwt_extended int RESTful API flask-jwt-extended TypeError:类型为&#39;function&#39;的对象不可JSON序列化 - flask-jwt-extended TypeError: Object of type 'function' is not JSON serializable TypeError:“ObjectId”类型的 Object 不是 JSON 可序列化使用 Flask 和 Z206E3718AFE7912FDAC1 - TypeError: Object of type 'ObjectId' is not JSON serializable using Flask and MongoDB Celery EncodeError(TypeError(&#39;响应类型的对象不是 JSON 可序列化的&#39;)) - Celery EncodeError(TypeError('Object of type Response is not JSON serializable')) “TypeError”类型的对象不是 JSON 可序列化的 - Object of type 'TypeError' is not JSON serializable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM