2015-09-13 5 views
0

Я просто пытаюсь отправить ответ на запрос клиента, но я не знаю, как декодировать ответ. Я всегда возвращаю строку.Как получить dict с почтовым запросом, json и cherrypy?

вот мой код сервера:

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()) 

Вот мой код клиента:

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() 

ответ

0

Ваш код сервера должен выглядеть следующим образом:

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()) 

json_out преобразует Dict в действительная строка JSON.

Также в вашем коде клиента у вас нет import json, чтобы использовать метод json от requests.