02 Step 1: The mock server (2/5)

  #!/usr/bin/env python3
  """Mock library API for testing a CrossPoint catalog plugin.
     python3 mock_library.py  -> listens on 0.0.0.0:8080
     Login: reader / secret.  Tokens expire after 120 s to exercise re-minting.
  """
  import json, os, secrets, time, urllib.parse, pathlib
  import sys
  sys.stdout.reconfigure(line_buffering=True)   # print immediately, also when piped
  from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
  
  USER, PASS = "reader", "secret"
  BOOKS_DIR = pathlib.Path(__file__).with_name("books")
  TOKENS = {}                     # token -> expiry
  SHELVES = {"new": "New arrivals", "fav": "Favorites"}
  
  def catalog():
      out = []
      for i, f in enumerate(sorted(BOOKS_DIR.glob("*.epub")), 1):
          out.append({"id": str(i), "title": f.stem.replace("-", " ").title(),
                      "author": "Unknown author", "file": f.name,
                      "shelf": "fav" if i % 2 else "new",
                      "summary": f"{f.stem} - {f.stat().st_size // 1024} KB"})
      return out
  
  class H(BaseHTTPRequestHandler):
      def send_json(self, code, obj):
          body = json.dumps(obj).encode()
          self.send_response(code)
          self.send_header("Content-Type", "application/json")
          self.send_header("Content-Length", str(len(body)))
          self.end_headers()
          self.wfile.write(body)
  
      def authed(self):
‹ PreviousReader file (.txt)Next ›