简体   繁体   中英

Error shown on flask when calling Flash restful service. TypeError: Object of type 'Response' is not JSON serializable

I am new to python and I am sort of debugging code which has been passed to me (also going through some links to learn python). I am setting up flask restful service and when I try to submit the inputs from the client and send the request, Flask restful shows the following error TypeError: Object of type 'Response' is not JSON serializable. Any idea what is causing this?

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 

below is the full trace

      [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

Try to use the built in flask function jsonify ( from flask import jsonify ): instead of response.json() , use jsonify(response) .

This resource may also be helpful: https://stackoverflow.com/a/47524294/6685140

Also, could you indicate on which line the error occurs? It would help in solving this greatly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM