I'm just trying to send a response to a client post request but I don't know how to decode the response. I always get a string back.
here's my server code:
import json
import cherryp
class Hey:
@cherrypy.expose
@cherrypy.tools.json_out()
def index(self):
a = {"a": "1", "b": "2", "c": "3"}
return json.dumps(a)
if __name__ == '__main__':
cherrypy.quickstart(Hey())
Here's my client code:
import requests
import json
headers = {'Content-type': 'application/json'}
def postServer():
resp = requests.post("http://localhost:8080/index", headers=headers)
return resp.json()
def test():
response = postServer()
print(response)
test()
Your server code should look like this:
import json
import cherrypy
class Hey:
@cherrypy.expose
@cherrypy.tools.json_out()
def index(self):
a = {"a": "1", "b": "2", "c": "3"}
return a
if __name__ == '__main__':
cherrypy.quickstart(Hey())
The json_out
will convert the dict into a valid JSON string.
Also in your client code you don't have to import json
to use the json
method from requests
.