BaseHTTPRequestHandler を使用して、Python で POST 要求の後に応答を取得しようとしています。問題を単純化するために、2 つの PHP ファイルがあります。
jquery_send.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function sendPOST() {
url1 = "jquery_post.php";
url2 = "http://localhost:9080";
$.post(url1,
{
name:'John',
email:'john@email.com'
},
function(response,status){ // Required Callback Function
alert("*----Received Data----*\n\nResponse : " + response + "\n\nStatus : " + status);
});
};
</script>
</head>
<body>
<button id="btn" onclick="sendPOST()">Send Data</button>
</body>
</html>
jquery_post.php
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: ". $name . ", email: ". $email; // Success Message
}
?>
jquery_send.phpを使用すると、POST リクエストを jquery_post.php に送信し、リクエストを正常に取得できます。ここで、 POST リクエストを jquery_post.php の代わりに Python BaseHTTPRequestHandlerに送信して、同じ結果を得たいと考えています。私はテストのためにこのPythonコードを使用しています:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
print("\n----- Request Start ----->\n")
content_length = self.headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0
print(self.rfile.read(length))
print("<----- Request End -----\n")
self.wfile.write("Received!")
self.send_response(200)
port = 9080
print('Listening on localhost:%s' % port)
server = HTTPServer(('', port), RequestHandler)
server.serve_forever()
POST リクエストは取得できますが、 jquery_send.phpでレスポンス ("Received!") を取得できません。私は何を間違っていますか?
編集:
つまり、BaseHTTPRequestHandler を使用して POST 要求を取得し、応答を送信するこの小さな Python コードがあります。
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
print(self.rfile.read(int(self.headers['Content-Length'])).decode("UTF-8"))
content = "IT WORKS!"
self.send_response(200)
self.send_header("Content-Length", len(content))
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(content)
print "Listening on localhost:9080"
server = HTTPServer(('localhost', 9080), RequestHandler)
server.serve_forever()
curlでレスポンスを取得できます
curl --data "param1=value1¶m2=value2" localhost:9080
しかし、Webページからajax/jqueryを使用して取得することはできません(サーバーはPOSTリクエストを正しく受け取りますが、Webページは応答を取得しません)。どうすればいいですか?