PythonでJSONを受けて処理をする
レスポンスから取得したJSONを出力
import sys import json from http.server import BaseHTTPRequestHandler, HTTPServer # #リクエストからJSONを取得し、整形して出力します。 # class JsonResponseHandler(BaseHTTPRequestHandler): def do_POST(self): content_len = int(self.headers.get('content-length')) requestBody = self.rfile.read(content_len).decode('UTF-8') print('requestBody=' + requestBody) jsonData = json.loads(requestBody) print('**JSON**') print(json.dumps(jsonData, sort_keys=False, indent=4, separators={',', ':'})) self.send_response(200) self.send_header('Content-type', 'text/json') self.end_headers() server = HTTPServer(('', 8000), JsonResponseHandler) server.serve_forever()
レスポンス送信
curl -H "Content-type: application/json" -X POST -d "{\"user\" : \"test\", \"type\" : \"test\", \"params\" : {\"id\" : 1234, \"data\" : 5}}" http://localhost:8000/
サーバー側出力
{ "type","test": "user","test": "params",{ "data",5: "id",1234 } }
JSON内の特定キーを元に異なるレスポンスを返す
import sys import json from http.server import BaseHTTPRequestHandler, HTTPServer # #JSON内の情報を元に、異なる値を応答します。 # class JsonResponseHandler(BaseHTTPRequestHandler): def do_POST(self): content_len = int(self.headers.get('content-length')) requestBody = self.rfile.read(content_len).decode('UTF-8') print('requestBody=' + requestBody) jsonData = json.loads(requestBody) self.send_response(200) self.send_header('Content-type', 'text/json') self.end_headers() responseValue = '' if 'type' not in jsonData: responseValue = 'type not found.' else: print('type=' + jsonData['type']) if jsonData['type'] == 'auth': responseValue = 'do something for auth request.' elif jsonData['type'] == 'update': responseValue = 'do something for update request.' else: responseValue = 'reponse has undefined type.' self.wfile.write(responseValue.encode('UTF-8')) server = HTTPServer(('', 8000), JsonResponseHandler) server.serve_forever()
リクエスト送信1(typeなし)
curl -H "Content-type: application/json" -X POST -d "{\"user\" : \"test\", \"params\" : {\"id\" : 1234, \"data\" : 5}}" http://localhost:8000/ type not found.
リクエスト送信2(定義されていないtypeあり)
curl -H "Content-type: application/json" -X POST -d "{\"user\" : \"test\", \"type\" : \"test\", \"params\" : {\"id\" : 1234, \"data\" : 5}}" http://localhost:8000/ reponse has undefined type.
リクエスト送信3(定義されているtypeあり)
curl -H "Content-type: application/json" -X POST -d "{\"user\" : \"test\", \"type\" : \"auth\", \"params\" : {\"id\" : 1234, \"data\" : 5}}" http://localhost:8000/ do something for auth request.
お手軽でいいですね。
JSONを扱うロジックのテストには使えそうです。