Tôi đang cố xây dựng một máy chủ REST đơn giản với SimpleHTTPServer trăn. Tôi đang gặp sự cố khi đọc dữ liệu từ bài đăng. Vui lòng cho tôi biết nếu tôi làm đúng.Đọc JSON từ SimpleHTTPServer Đăng dữ liệu
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()
Các tập tin index.html
<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>
Các simplejson thất bại trong việc tải các json từ thông điệp POST. Tôi không quen thuộc với mã hóa web và tôi thậm chí không chắc chắn nếu những gì tôi đang làm là đúng cho việc tạo ra một máy chủ API REST đơn giản. Tôi đánh giá cao sự giúp đỡ của bạn.
Cũng xin vui lòng cho tôi biết nếu đây không phải là con đường để đi và nếu có một django là cách duy nhất để đi. –