似たようなタイトルが続いていますが
今回は、サーバー自体の挙動を変えれば
前回、前々回のようにCGIにせずともJSONを返せるという話。
セットアップ、動かし方については前々回
PythonによるCGIが動くHTTPサーバーを簡単に用意する - てけとーぶろぐ。
をどうぞ。
サーバー本体のプログラムを「server.py」として作成。
同じディレクトリー内にあるJSONファイルの名前でアクセスすると
そのファイルの内容を返すようになっているので
合わせて「test.json」も作成。
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): 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()
{ "key":"value" }
クライアント側のプログラムを「client.py」として作成。「test」にアクセスする。
import requests service_name = 'test' r = requests.post('http://localhost:8080/' + service_name, json={"key": "value"}) print(r.status_code) print(r.json())