util.httpsrv

Simple HTTP server implementation that allows adding arbitrary paths, backed by (different) filesystem paths.

Ie.
with BackgroundHTTPServer(‘127.0.0.1’, 8080) as srv:

srv.add_file(‘/on/disk/file.txt’, ‘/visible.txt’) srv.add_file(‘/on/disk/dir’, ‘/somedir’) srv.start() …

Any HTTP GET requests for ‘/visible.txt’ will receive the contents of ‘/on/disk/file.txt’ (or 404). Any HTTP GET requests for ‘/somedir/aa/bb’ will receive the contents of ‘/on/disk/dir/aa/bb’ (or 404).

You can call ‘srv.add_*’ functions even after calling .start(), however be aware that this creates a potential race condition with the request- handling code, so make sure nothing queries the server while new entries are being added.

Port can also be specified as 0 (just like for Python’s socketserver) which will cause a random unused port to be allocated by the OS kernel. You can then retrieve it from the return tuple of .start():

with BackgroundHTTPServer(‘127.0.0.1’, 0) as srv:

host, port = srv.start() # ‘host’ will be ‘127.0.0.1’ with port being >0

You can also use the server without a context manager, assuming you take care of stopping it (manually, via try/finally, etc.):

srv = BackgroundHTTPServer(‘127.0.0.1’, 0) try:

host, port = srv.start() …

finally:

srv.stop()

Module Contents

class util.httpsrv.BackgroundHTTPServer(host, port)
server = None
file_mapping
dir_mapping
requested_address
firewalld_zones = []
add_file(fs_path, url_path=None)

Map a filesystem path to a file to virtual location on the HTTP server, so that requests to the virtual location get the contents of the real file on the filesystem.

‘fs_path’ can be relative or absolute, ‘url_path’ can have an optional leading ‘/’ that is automatically ignored

For example:

# GET /users will receive contents of /etc/passwd .add_file(‘/etc/passwd’, ‘users’) # GET /some/file will get contents of tmpfile (relative to CWD) .add_file(‘tmpfile’, ‘some/file’) # GET /testfile will get the contents of testfile (in CWD) .add_file(‘testfile’)

add_dir(fs_path, url_path=None)

Map a filesystem directory to a virtual location on the HTTP server, see add_file() for details.

For example:

# GET /config/passwd will receive the contents of /etc/passwd .add_dir(‘/etc’, ‘config’) # GET /repo/repodata/repomd.xml gets /tmp/tmp.12345/repodata/repomd.xml .add_dir(‘/tmp/tmp.12345’, ‘repo’) # GET /testdir/123 will get the contents of testdir/123 (in CWD) .add_dir(‘testdir’)

start()

Start the HTTP server - open a listening socket, start serving requests.

The server can be shut down either by exiting a context manager (if it was created by the context manager), or by calling .stop() manually.

Returns a (host, port) tuple the server is listening on.

stop()

Stop the HTTP server, close the listening socket.