Skip to content

Instantly share code, notes, and snippets.

@Philmist
Created May 25, 2021 04:09
Show Gist options
  • Save Philmist/d23215353a991f6b7bbcf7418a999ec2 to your computer and use it in GitHub Desktop.
Save Philmist/d23215353a991f6b7bbcf7418a999ec2 to your computer and use it in GitHub Desktop.
使い捨て簡易HTTP POST受けサーバー
from http.server import HTTPServer, SimpleHTTPRequestHandler
import cgi
import logging
import json
logging.basicConfig(level=logging.DEBUG)
class RecognizeTextHandler(SimpleHTTPRequestHandler):
FILE_NAME = "recognized.txt"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_GET(self):
logging.error(self.headers)
self.send_response_only(400)
def do_POST(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
encoding = "utf-8"
if "Content-Type" in self.headers:
mimetype, options = cgi.parse_header(self.headers["Content-Type"])
if "charset" in options:
encoding = options["charset"]
data_string = self.rfile.read(int(self.headers["Content-Length"]))
received_text = data_string.decode(encoding)
json_data = json.loads(received_text)
logging.info(json_data["text"])
with open(self.FILE_NAME, mode="a", encoding="utf-8") as f:
f.write(json_data["text"] + "\n")
send_data = b"OK"
try:
self.wfile.write(bytes(send_data))
except ConnectionResetError:
pass
def main():
httpd = HTTPServer(("localhost", 9090), RecognizeTextHandler)
logging.info("START")
httpd.serve_forever()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment