Python CGI and json dumps

3.7k Views Asked by At

I'm using python for a light web application based on BaseHTTPServer and CGIHTTPServer.

I have a little issue with an ajax call, which retrieves a dictionary to fill a select widget. Being "list" the select ID this is the javascript code to dynamically fill the options :

$.getJSON("/web/ajax/list.py", function(result) {
    $.each(result, function(key, value){
        $("#list").append("<option id=" + key + ">" + value + "</option>");
    });
});

In the server side file list.py I can't simply dump the dictionary contents using json.dumps but I'm forced to print some empty lines before doing so:

options = {}
options[1] = "option 1"
options[2] = "option 2"
options[3] = "option 3"

# Whitout these two lines it doesn't work!!
print """
"""

import json
print json.dumps(options)

Any ideas why this doesn't work just by dumping the dictionary ?

I'd like to get rid of the extra print.

2

There are 2 best solutions below

0
On BEST ANSWER

cgi has a pretty strict idea of what you are supposed to print out for the server. Specifically, you need to provide the set of response headers, the response body, and an empty line between the two so the server knows where the headers stop and the body starts.

That is to say, the new line is not superfluous; and in fact, you should probably add some more:

body = json.dumps(...)

print "Status: 200 OK"
print "Content-Type: application/json"
print "Length:", len(body)
print ""
print body
0
On

Pretty close... There is no HTTP header "Length", and while Content-Length is not strictly required, if you know it add it like this:

print "Status: 200 OK"
print "Content-Type: application/json"
print "Content-Length: %d" % (len(body))
print ""
print body