调用Flash Restful服务时,烧瓶上显示错误。 TypeError:“ Response”类型的对象不可JSON序列化

时间:2019-01-17 13:28:37

标签: python json flask serializable

我是python的新手,并且是某种已传递给我的调试代码(还通过一些链接来学习python)。 我正在设置flask restful服务,当我尝试从客户端提交输入并发送请求时,Flask restful显示以下错误 TypeError:“ Response”类型的对象不可JSON序列化。 知道是什么原因造成的吗?

from flask import flash
import requests
import base64
import json

show= ''
makes= {}
inputData={
  "inputs": [
    {
      "name": "type",
      "value": ""
    },
    {
      "name": "product",
      "value": ""
    }
  ]
}

from flask import flash
import requests
import base64
import json

def callProductList(form):
global show


server= '{values}'
uid= '{values}'
pwd= '{values}'
clientId= '{values}'
clientPassword= '{values}'
Server= '{values}'


inputData["inputs"][0]["value"]= form.type.data
inputData["inputs"][1]["value"]= form.product.data



loginCredentials={"grant_type":"password","username":uid,"password":pwd}
appBinding= clientId + ':' + clientSecret
appBinding64= base64.b64encode(bytes(appBinding, 'utf-8'))
url= "{values}" % (server)

headers = {"Content-Type":"application/x-www-form-urlencoded", "Authorization":"Basic "}
headers["Authorization"]= "Basic " + appBinding64.decode('ascii')
response = requests.post(url, headers=headers, data=loginCredentials)

if response.status_code < 200 or response.status_code >= 300:
    flash(response)
    flash('Error receiving user token!')
    return
token= response.json()['access_token']


inputDataJSON= json.dumps(inputData)
url= "{values}" % (server, Server)
headers = {"Content-Type":"application/json", "Authorization":"Holder "}
headers["Authorization"]= "Holder " + token
response = requests.post(url, headers=headers, data=inputDataJSON)

if response.status_code < 200 or response.status_code >= 300:
    flash(response)
    flash('Error calling Server!')
    return

dataFound= True
for mk in response.json()['outputs']:
    try:
        makes[mk['name']]= mk['value'].split(',')
    except:
        dataFound= False
        break;

if not dataFound:
    show= 'Nothing Found!'
    makes.clear()
else:
    show= 'Records found!'

return 

下面是完整的跟踪

      [2019-01-17 08:45:08,074] ERROR in app: Exception on /makes [POST]
Traceback (most recent call last):
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1632, in finalize_request
    response = self.process_response(response)
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/app.py", line 1858, in process_response
    self.save_session(ctx.session, response)
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/app.py", line 924, in save_session
    return self.session_interface.save_session(self, session, response)
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/sessions.py", line 363, in save_session
    val = self.get_signing_serializer(app).dumps(dict(session))
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/itsdangerous.py", line 565, in dumps
    payload = want_bytes(self.dump_payload(obj))
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/itsdangerous.py", line 847, in dump_payload
    json = super(URLSafeSerializerMixin, self).dump_payload(obj)
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/itsdangerous.py", line 550, in dump_payload
    return want_bytes(self.serializer.dumps(obj))
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/sessions.py", line 85, in dumps
    return json.dumps(_tag(value), separators=(',', ':'))
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/json.py", line 123, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "/opt/user1inside/anaconda3/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/opt/user1inside/anaconda3/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/opt/user1inside/anaconda3/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/opt/user1inside/anaconda3/lib/python3.6/site-packages/flask/json.py", line 80, in default
    return _json.JSONEncoder.default(self, o)
  File "/opt/user1inside/anaconda3/lib/python3.6/json/encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'Response' is not JSON serializable

1 个答案:

答案 0 :(得分:0)

尝试使用内置的烧瓶功能jsonifyfrom flask import jsonify):使用response.json()代替jsonify(response)

此资源可能也有帮助: https://stackoverflow.com/a/47524294/6685140

此外,您能指出错误发生在哪一行吗?这将极大地解决这个问题。