I am trying to build a simple REST server with python SimpleHTTPServer. I am having problem reading data from the post message. Please let me know if I am doing it right.
from SimpleHTTPServer import SimpleHTTPRequestHandler
import SocketServer
import simplejson
class S(SimpleHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
print "got get request %s" % (self.path)
if self.path == '/':
self.path = '/index.html'
return SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
print "got post!!"
content_len = int(self.headers.getheader('content-length', 0))
post_body = self.rfile.read(content_len)
test_data = simplejson.loads(post_body)
print "post_body(%s)" % (test_data)
return SimpleHTTPRequestHandler.do_POST(self)
def run(handler_class=S, port=80):
httpd = SocketServer.TCPServer(("", port), handler_class)
print 'Starting httpd...'
httpd.serve_forever()
The index.html file
<html>
<title>JSON TEST PAGE</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "http://128.107.138.51:8080",
type: "POST",
data: {txt1: $("#json_text").val()},
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My Web Page</h1>
<div id="resultDivContainer"></div>
<form>
<textarea name="json_text" id="json_text" rows="50" cols="80">
[{"resources": {"dut": "any_ts", "endpoint1": "endpoint", "endpoint2": "endpoint"}},
{"action": "create_conference", "serverName": "dut", "confName": "GURU_TEST"}]
</textarea>
<button type="button" onclick="JSONTest()">Generate Test</button>
</form>
</body>
</html>
The SimpleJson fails to load the json from the POST message. I am not familiar with web coding and I am not even sure if what I am doing is right for creating a simple REST API server. I appreciate your help.
SimpleHTTPRequestHandler does not support POST. It's very simple indeed. Check out Klein whose server is a bit more full-featured.
There's an example of a json PUT (pretty close to POST) here: https://pypi.python.org/pypi/klein/0.2.3
Thanks matthewatabet for the klein idea. I figured a way to implement it using BaseHTTPHandler. The code below.
And the corresponding html page