Skip to content

http_server

Simple HTTP server with authorization support for testing.

Serves files from the current (or given) folder over HTTP, requiring authorization - bearer or basic - for write operations (PUT/DELETE), while reads are served without authorization.

HandlerException

Bases: Exception

Exception raised for HTTP handler errors with status code and message.

Handlers raise it - typically out of _check_authorization() - and the do_PUT()/do_DELETE() methods convert it into an HTTP error response.

Attributes:

Name Type Description
code

The HTTP status code.

message

The error message string.

explain

The explanation string.

Source code in py_misc_utils/http_server.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class HandlerException(Exception):
  """Exception raised for HTTP handler errors with status code and message.

  Handlers raise it - typically out of _check_authorization() - and the
  do_PUT()/do_DELETE() methods convert it into an HTTP error response.

  Attributes:
    code: The HTTP status code.
    message: The error message string.
    explain: The explanation string.
  """

  def __init__(self, code, message, explain):
    """Initialize the exception with HTTP error details.

    Args:
      code: The HTTP status code (e.g. 401, 403, 500).
      message: A short error message.
      explain: A longer explanation string.
    """
    super().__init__()
    self.code = code
    self.message = message
    self.explain = explain

HTTPRequestHandler

Bases: SimpleHTTPRequestHandler

HTTP request handler with authorization for write operations.

Extends SimpleHTTPRequestHandler to add bearer and basic authentication checking for PUT and DELETE operations. OPTIONS is supported for CORS preflight requests.

Source code in py_misc_utils/http_server.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
class HTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
  """HTTP request handler with authorization for write operations.

  Extends SimpleHTTPRequestHandler to add bearer and basic authentication
  checking for PUT and DELETE operations. OPTIONS is supported for CORS
  preflight requests.
  """

  def _check_authorization(self, op, path):
    """Check authorization for an operation on a path.

    Validates the Authorization header against the server's auth configuration.
    Supports bearer and basic auth types.

    Args:
      op: The operation string (e.g. 'PUT', 'DELETE').
      path: The resource path being accessed.

    Raises:
      HandlerException: With appropriate HTTP status code if authorization
        fails or is not configured.
    """
    hauth = self.headers['Authorization']
    if hauth is None:
      raise HandlerException(401, 'Unauthorized',
                             f'Action not allowed on "{self.path}"\n')
    if self._args.auth is None:
      self.log_message(f'Client request needs authorization but server not configured ' \
                       f'for it: {op} {self.path}')
      raise HandlerException(403, 'Forbidden', f'Action not allowed on "{self.path}"\n')

    try:
      auth_type, auth_config = [x.strip() for x in hauth.split(' ', maxsplit=1)]

      auth_type = auth_type.lower()
      if auth_type == 'bearer':
        token = base64.b64decode(auth_config).decode()
        if token != self._args.auth:
          self.log_message(f'Client authorization invalid: {op} {self.path} {token}')
          raise HandlerException(403, 'Forbidden',
                                 f'Action not allowed on "{self.path}"\n')
      elif auth_type == 'basic':
        creds = base64.b64decode(auth_config).decode()
        user, passwd = creds.split(':', maxsplit=1)

        # Very crude auth!
        if passwd != self._args.auth:
          self.log_message(
              f'Client authorization invalid: {op} {self.path} {user}:{passwd}')
          raise HandlerException(403, 'Forbidden',
                                 f'Action not allowed on "{self.path}"\n')
      else:
        raise HandlerException(403, 'Forbidden',
                               f'Authorization not supported: {hauth}\n')
    except HandlerException:
      raise
    except Exception as ex:  # noqa: BLE001 -- request-boundary: auth-path failures are converted to a 500 response
      raise HandlerException(500, 'Internal Server Error', f'Internal error: {ex}\n')

  def do_OPTIONS(self):
    """Handle OPTIONS requests with CORS headers.

    Responds with 200 OK and lists allowed methods - no authorization
    check is performed, letting clients probe the server capabilities.
    """
    self.send_response(200, 'OK')
    self.send_header('Allow', 'GET,POST,PUT,OPTIONS,HEAD,DELETE')
    self.send_header('Content-Length', '0')
    self.end_headers()

  def do_DELETE(self):
    """Handle DELETE requests with authorization check.

    Deletes the file at the requested path if authorized.

    Example:
      import argparse
      import base64
      import functools
      import http.server
      import tempfile
      import threading

      import requests

      from py_misc_utils import http_server as hs

      # Serve a scratch folder, with authorization required for writes.
      handler = hs.ClassWrapper(hs.HTTPRequestHandler,
                                _args=argparse.Namespace(auth='s3cret'))
      td = tempfile.mkdtemp()
      server = http.server.ThreadingHTTPServer(
          ('127.0.0.1', 0), functools.partial(handler, directory=td))
      threading.Thread(target=server.serve_forever, daemon=True).start()
      url = 'http://127.0.0.1:{}'.format(server.server_address[1])

      # Writes need the authorization header - others are rejected.
      token = base64.b64encode(b's3cret').decode()
      resp = requests.put(url + '/hello.txt', data=b'hi there',
                          headers={'Authorization': 'Bearer ' + token})
      assert resp.status_code == 201

      # Reads are served without authorization.
      assert requests.get(url + '/hello.txt').content == b'hi there'
      server.shutdown()
      server.server_close()
    """
    path = _sanitize_path(self.translate_path(self.path))
    if path is None:
      self.send_error(403,
                      message='Forbidden',
                      explain=f'Action not allowed on "{self.path}"\n')
    else:
      try:
        self._check_authorization('DELETE', path)

        os.remove(path)

        self.send_response(200, 'OK')
        self.send_header('Content-Length', '0')
        self.end_headers()
      except HandlerException as ex:
        self.send_error(ex.code, message=ex.message, explain=ex.explain)
      except OSError as ex:
        self.send_error(500,
                        message='Internal Server Error',
                        explain=f'Internal error: {ex}\n')

  def do_PUT(self):
    """Handle PUT requests with authorization check.

    Creates or overwrites the file at the requested path if authorized.

    See do_DELETE() for a full client/server example.
    """
    path = _sanitize_path(self.translate_path(self.path))
    if path is None:
      self.send_error(403,
                      message='Forbidden',
                      explain=f'Action not allowed on "{self.path}"\n')
    else:
      try:
        self._check_authorization('PUT', path)

        os.makedirs(os.path.dirname(path), exist_ok=True)

        chunked_headers = dict()
        with open(path, 'wb') as f:
          f.writelines(_read_stream(self.headers, self.rfile, chunked_headers))

        self.send_response(201, 'Created')
        self.end_headers()
      except HandlerException as ex:
        self.send_error(ex.code, message=ex.message, explain=ex.explain)
      except Exception as ex:  # noqa: BLE001 -- handler boundary: convert any request-processing failure to a clean 500 response
        self.send_error(500,
                        message='Internal Server Error',
                        explain=f'Internal error: {ex}\n')

do_OPTIONS()

Handle OPTIONS requests with CORS headers.

Responds with 200 OK and lists allowed methods - no authorization check is performed, letting clients probe the server capabilities.

Source code in py_misc_utils/http_server.py
173
174
175
176
177
178
179
180
181
182
def do_OPTIONS(self):
  """Handle OPTIONS requests with CORS headers.

  Responds with 200 OK and lists allowed methods - no authorization
  check is performed, letting clients probe the server capabilities.
  """
  self.send_response(200, 'OK')
  self.send_header('Allow', 'GET,POST,PUT,OPTIONS,HEAD,DELETE')
  self.send_header('Content-Length', '0')
  self.end_headers()

do_DELETE()

Handle DELETE requests with authorization check.

Deletes the file at the requested path if authorized.

Example
import argparse
import base64
import functools
import http.server
import tempfile
import threading

import requests

from py_misc_utils import http_server as hs

# Serve a scratch folder, with authorization required for writes.
handler = hs.ClassWrapper(hs.HTTPRequestHandler,
                          _args=argparse.Namespace(auth='s3cret'))
td = tempfile.mkdtemp()
server = http.server.ThreadingHTTPServer(
    ('127.0.0.1', 0), functools.partial(handler, directory=td))
threading.Thread(target=server.serve_forever, daemon=True).start()
url = 'http://127.0.0.1:{}'.format(server.server_address[1])

# Writes need the authorization header - others are rejected.
token = base64.b64encode(b's3cret').decode()
resp = requests.put(url + '/hello.txt', data=b'hi there',
                    headers={'Authorization': 'Bearer ' + token})
assert resp.status_code == 201

# Reads are served without authorization.
assert requests.get(url + '/hello.txt').content == b'hi there'
server.shutdown()
server.server_close()
Source code in py_misc_utils/http_server.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def do_DELETE(self):
  """Handle DELETE requests with authorization check.

  Deletes the file at the requested path if authorized.

  Example:
    import argparse
    import base64
    import functools
    import http.server
    import tempfile
    import threading

    import requests

    from py_misc_utils import http_server as hs

    # Serve a scratch folder, with authorization required for writes.
    handler = hs.ClassWrapper(hs.HTTPRequestHandler,
                              _args=argparse.Namespace(auth='s3cret'))
    td = tempfile.mkdtemp()
    server = http.server.ThreadingHTTPServer(
        ('127.0.0.1', 0), functools.partial(handler, directory=td))
    threading.Thread(target=server.serve_forever, daemon=True).start()
    url = 'http://127.0.0.1:{}'.format(server.server_address[1])

    # Writes need the authorization header - others are rejected.
    token = base64.b64encode(b's3cret').decode()
    resp = requests.put(url + '/hello.txt', data=b'hi there',
                        headers={'Authorization': 'Bearer ' + token})
    assert resp.status_code == 201

    # Reads are served without authorization.
    assert requests.get(url + '/hello.txt').content == b'hi there'
    server.shutdown()
    server.server_close()
  """
  path = _sanitize_path(self.translate_path(self.path))
  if path is None:
    self.send_error(403,
                    message='Forbidden',
                    explain=f'Action not allowed on "{self.path}"\n')
  else:
    try:
      self._check_authorization('DELETE', path)

      os.remove(path)

      self.send_response(200, 'OK')
      self.send_header('Content-Length', '0')
      self.end_headers()
    except HandlerException as ex:
      self.send_error(ex.code, message=ex.message, explain=ex.explain)
    except OSError as ex:
      self.send_error(500,
                      message='Internal Server Error',
                      explain=f'Internal error: {ex}\n')

do_PUT()

Handle PUT requests with authorization check.

Creates or overwrites the file at the requested path if authorized.

See do_DELETE() for a full client/server example.

Source code in py_misc_utils/http_server.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def do_PUT(self):
  """Handle PUT requests with authorization check.

  Creates or overwrites the file at the requested path if authorized.

  See do_DELETE() for a full client/server example.
  """
  path = _sanitize_path(self.translate_path(self.path))
  if path is None:
    self.send_error(403,
                    message='Forbidden',
                    explain=f'Action not allowed on "{self.path}"\n')
  else:
    try:
      self._check_authorization('PUT', path)

      os.makedirs(os.path.dirname(path), exist_ok=True)

      chunked_headers = dict()
      with open(path, 'wb') as f:
        f.writelines(_read_stream(self.headers, self.rfile, chunked_headers))

      self.send_response(201, 'Created')
      self.end_headers()
    except HandlerException as ex:
      self.send_error(ex.code, message=ex.message, explain=ex.explain)
    except Exception as ex:  # noqa: BLE001 -- handler boundary: convert any request-processing failure to a clean 500 response
      self.send_error(500,
                      message='Internal Server Error',
                      explain=f'Internal error: {ex}\n')

ClassWrapper

Wraps a class to inject constructor keyword arguments as attributes.

When called, creates a new instance with the wrapped class and updates its dict with the stored kwargs before calling init. Also intercepts setattr to store attribute assignments in _kwargs - so that later attribute assignments on the wrapper are seen by instances created afterwards.

PRIVATE_ATTRIBUTES: Set of attribute names that are not stored in _kwargs.

Example
from py_misc_utils import http_server as hs


class Greeting:
  def __init__(self, name):
    self.name = name

wrapped = hs.ClassWrapper(Greeting)
obj = wrapped('Ada')
assert obj.name == 'Ada'
# Attributes assigned on the wrapper are injected into later instances.
wrapped.timeout = 30
obj2 = wrapped('Grace')
assert obj2.timeout == 30 and obj2.name == 'Grace'
Source code in py_misc_utils/http_server.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
class ClassWrapper:
  """Wraps a class to inject constructor keyword arguments as attributes.

  When called, creates a new instance with the wrapped class and updates its
  __dict__ with the stored kwargs before calling __init__. Also intercepts
  __setattr__ to store attribute assignments in _kwargs - so that later
  attribute assignments on the wrapper are seen by instances created
  afterwards.

  PRIVATE_ATTRIBUTES: Set of attribute names that are not stored in _kwargs.

  Example:
    from py_misc_utils import http_server as hs


    class Greeting:
      def __init__(self, name):
        self.name = name

    wrapped = hs.ClassWrapper(Greeting)
    obj = wrapped('Ada')
    assert obj.name == 'Ada'
    # Attributes assigned on the wrapper are injected into later instances.
    wrapped.timeout = 30
    obj2 = wrapped('Grace')
    assert obj2.timeout == 30 and obj2.name == 'Grace'
  """

  PRIVATE_ATTRIBUTES = {'_cls', '_kwargs'}  # noqa: RUF012 -- read-only class constant

  # Attribute names excluded from _kwargs storage.

  def __init__(self, cls, **kwargs):
    """Initialize the wrapper with a class and keyword arguments.

    Args:
      cls: The class to wrap.
      **kwargs: Keyword arguments to inject into wrapped instances.
    """
    self._cls = cls
    self._kwargs = kwargs

  def __setattr__(self, name, value):
    """Set an attribute, storing non-private ones in _kwargs.

    Args:
      name: The attribute name.
      value: The value to set.
    """
    sdict = super().__getattribute__('__dict__')
    sdict[name] = value
    if name not in ClassWrapper.PRIVATE_ATTRIBUTES:
      sdict['_kwargs'][name] = value

  def __call__(self, *args, **kwargs):
    """Create and initialize a new instance of the wrapped class.

    The instance's __dict__ is updated with stored kwargs before __init__
    is called, allowing http.server.test() to inject data.

    Args:
      *args: Positional arguments for the wrapped class __init__.
      **kwargs: Keyword arguments for the wrapped class __init__.

    Returns:
      A new instance of the wrapped class.
    """
    obj = self._cls.__new__(self._cls, *args, **kwargs)
    # Add ctor supplied data and data planted by the http.server.test() API
    # (talking about bad API design).
    obj.__dict__.update(self._kwargs)
    obj.__init__(*args, **kwargs)

    return obj