sending JSON response from HTTP server in python

1.9k views Asked by At

I'm trying to send data as a JSON object from a python HTTP server to a client. Here is the do_POST function I use to get the client request:

def do_POST(self):
    if None != re.search('/compile/*', self.path):
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        print "ctype = %s", ctype
        if ctype == 'application/json':
            length = int(self.headers.getheader('content-length'))
            data = json.loads(self.rfile.read(length))
            response = doEverything(data["userId"], data["files"])
            ##response = json.dump(response, self.wfile)                                                                                                                                                       
            response = json.dumps(response)
            self.send_response(0)
            self.end_headers()
            self.wfile.write(str(response))
            print 'everything ok'
        else:
            data = {}
            self.send_response(200)
            self.end_headers()
            print 'not application/json'
    else:
        self.send_response(403)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        print 'not /compile/*'

    return

There must be something I do wrong cause the client never get any response. (And yes, the output print "everything ok"). I replaced self.wfile.write(response) by self.wfile.write(str(response)) to test, the both don't work.

Thank for the help, don't hesitate to ask if you need more code

0

There are 0 answers