PythonによるJSONを返すHTTPサーバーを簡単に用意する - てけとーぶろぐ。の続き。
サーバーにクライアントから受け取ったJSONを表示する機能を追加する。
do_json_service() に3行追加。
from http.server import HTTPServer, BaseHTTPRequestHandler import sys, json import os.path import glob class Handler(BaseHTTPRequestHandler): def do_POST(self): service_names = [] files = glob.glob('./*.json') for file in files: basename = os.path.basename(file) service_names.append(os.path.splitext(basename)[0]) for name in service_names: if self.path == ('/' + name): self.do_json_service(name) def do_json_service(self, name): b = self.rfile.read(int(self.headers['Content-Length'])) s = json.loads(b.decode("utf-8")) print(json.dumps(s, indent=4, sort_keys=True)) f = open(name + ".json") result_json = json.load(f) f.close() self.send_response(200) self.send_header('Content-type','application/json') self.end_headers() self.wfile.write(json.dumps(result_json).encode('UTF-8')) PORT = 8080 httpd = HTTPServer(("", PORT), Handler) httpd.serve_forever()