File: echo_server.py

package info (click to toggle)
cloud-init 25.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,412 kB
  • sloc: python: 135,894; sh: 3,883; makefile: 141; javascript: 30; xml: 22
file content (37 lines) | stat: -rw-r--r-- 1,025 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python3
"""
Very simple HTTP daemon server in python for incoming POST data to stdout.
Each line represents a request's POST data a dictionary.
"""
import contextlib
import pathlib
from http.server import BaseHTTPRequestHandler, HTTPServer

OUTFILE = pathlib.Path("/var/tmp/echo_server_output")


class Server(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):
        self._set_response()

    def do_POST(self):
        content_length = int(self.headers["Content-Length"])
        post_data = self.rfile.read(content_length).decode("utf-8")
        with OUTFILE.open("a") as f:
            f.write(f"{post_data}\n")
        self._set_response()

    def log_message(self, *args, **kwargs):
        pass


server_address = ("", 55555)
httpd = HTTPServer(server_address, Server)
with contextlib.suppress(KeyboardInterrupt):
    httpd.serve_forever()
httpd.server_close()