A Python HTTP service in front of the core

The first way to call the core is the blunt one: start a new C# process for every request, hand it the line as an argument, read its one line of output and return it. It is the way a script calls a tool it did not write, and it needs nothing from the core but the built program. The Python layer is an http.server, which is in the standard library.

The service

The handler reads the request body as the line, calls price and writes the answer with a text content type. make_handler takes the price function as an argument, which is what lets the tests of the Python page run the handler without a C# process. Two settings come from the environment: CORE_CLI is the path of the built C# program, because the folder of the program is not the same in a checkout and in an image, and BIND_HOST is the address the server binds, because a server bound to 127.0.0.1 is unreachable from outside the machine or the container it runs in:

#!/usr/bin/env python3 """An HTTP front for the C# core: one process per request.""" import os import subprocess import sys from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path ROOT = Path(__file__).resolve().parent.parent CLI = Path(os.environ.get("CORE_CLI", ROOT / "src" / "Cli" / "bin" / "Release" / "net10.0" / "Cli.dll")) def price(line: str, cli: Path = CLI) -> str: """Run the C# CLI for one line and return its answer.""" result = subprocess.run( ["dotnet", str(cli), line], capture_output=True, text=True, check=False, timeout=10, ) if result.returncode != 0: return f"err process {result.returncode}" return result.stdout.strip() def make_handler(price_function): class Handler(BaseHTTPRequestHandler): def do_POST(self): length = int(self.headers.get("Content-Length", "0")) line = self.rfile.read(length).decode("utf-8").strip() body = price_function(line).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, format, *args): pass return Handler if __name__ == "__main__": host = os.environ.get("BIND_HOST", "127.0.0.1") port = int(os.environ.get("BIND_PORT", sys.argv[1] if len(sys.argv) > 1 else 8080)) print(f"listening on http://{host}:{port}", flush=True) HTTPServer((host, port), make_handler(price)).serve_forever()

The caller

The caller is the smallest useful client: one request with urllib and the body printed:

#!/usr/bin/env python3 """Send one request line to the service and print the answer.""" import sys import urllib.request port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080 line = sys.argv[2] if len(sys.argv) > 2 else "sku=pen qty=2 unit=1.50" request = urllib.request.Request( f"http://127.0.0.1:{port}/price", data=line.encode(), method="POST" ) with urllib.request.urlopen(request) as response: print(response.read().decode())

The run

The service was started on port 8080 and the caller sent two lines, a valid one and an invalid one:

python3 python/service.py 8080
echo "status: $?"

listening on http://127.0.0.1:8080

python3 python/post.py 8080 "sku=pen qty=2 unit=1.50"
python3 python/post.py 8080 "sku=pen qty=0 unit=1.50"

ok 3.00 0.60 3.60
err qty must be 1 to 100

The two answers are the answers of the C# program, character for character: the Python layer did not validate anything and did not price anything. That is the property to want from such a layer. The day the core changes a rule, the service changes nothing.

The path and the address

The two settings are what a container needs. The path of the program is the folder of the checkout by default and an absolute path in an image, where the published files are copied to /app/core; the address is 127.0.0.1 by default, which is right for a test and wrong for a container, because the port is then unpublished to the host. The run below sets both variables and sends one request:

BIND_HOST=0.0.0.0 CORE_CLI=/tmp/core/Cli.dll python3 python/service.py 8081
python3 python/post.py 8081 "sku=pen qty=2 unit=1.50"

listening on http://0.0.0.0:8081
ok 3.00 0.60 3.60

The address in the log is the real one the server bound, so a wrong value is visible before the first request. A container image of this page sets BIND_HOST=0.0.0.0 and CORE_CLI to the copied program; the deployment page of the group shows the file.

The cost

A process per request is not cheap: the timing page measured 85.309 milliseconds per call in this way, against 0.047 through the daemon and 2.271 through the API. For a user who sends one request and waits, 85 milliseconds is invisible; for a loop of a thousand requests it is a minute and a half of starting runtimes.

The next page is that daemon: the same program, one process, many lines.

Exercises

  1. Add a GET /health route to the Python service.
  2. Return a 400 status for an answer that starts with err and see what urllib does with it.
  3. Measure the service with the timing page of the client and compare it with the direct subprocess number.
  4. Make the handler reuse one C# process for all requests and describe what changed.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the Python service do for one request?

    Answer

    It runs the built C# program with the line as an argument

    The subprocess.run call is in the price function.

  2. Why does the service validate nothing?

    Answer

    The core owns the rules, and the layer stays a transport

    The answers are the answers of the C# program.

  3. What does this program print? Console.WriteLine("ok 3.00 0.60 3.60");

    Answer

    ok 3.00 0.60 3.60

    Two at 1.50 is the answer of the core.

  4. How much did one call cost this way?

    Answer

    88.566 milliseconds, the median of five runs

    The timing page measured the three ways.

  5. What does this program print? Console.WriteLine("err qty must be 1 to 100");

    Answer

    err qty must be 1 to 100

    The second request of the demo is the invalid quantity.

  6. Why does subprocess.run have a timeout?

    Answer

    A hung program must not hang the service

    The page gives it ten seconds.

  7. What does make_handler take?

    Answer

    The price function, so a test can pass a fake one

    The tests page uses it with a lambda.

  8. What does this program print? Console.WriteLine("ok 2.50 0.50 3.00");

    Answer

    ok 2.50 0.50 3.00

    Ten at 0.25 is a valid request of the page.

  9. What is the bottleneck of this service?

    Answer

    One process per request and one thread for the server

    The page names both limits.

  10. When is this design good enough?

    Answer

    When a request is rare and 88 milliseconds is invisible

    The page says so and offers the daemon for the loop.

The C# code on this page was built with the .NET SDK 10.0.303 and the Python code was run with Python 3.14.10, on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev