blinkenxmas.httpd
The blinkenxmas.httpd module extends the standard library’s
http.server with handling functions for form-data, JSON content, and a
mechanism to route requests to static content, chameleon generated
content, or dynamic functions.
It also defines the HTTPThread class, the main thread used by the
bxweb application to service HTTP clients, the route()
decorator used to associate handler functions with their HTTP virtual path (see
blinkenxmas.routes), and the animation() decorator used to declare
LED animation generators for the main interface.
HTTP handlers
- blinkenxmas.httpd.route(pattern, command='GET')[source]
Decorator that associates a route with a function
The pattern specifies the route that is to be matched. Within the pattern, angle-bracket words designate variable sections of the route that will be passed to like-named parameters in the associated function. The command (which defaults to ‘GET’) specifies which HTTP command the route will match.
The associated function must accept the mandatory “request” parameter first, which will contain the associated
HTTPRequestHandler, plus any parameters implied by<sections>in the pattern. It must return aHTTPResponseobject, orNoneif (for some reason) the route doesn’t match.For example, the following declaration will match the single route “/index.html”:
@route('/index.html') def homepage(request): return HTTPResponse(request, body='Hello, world!')
The following declaration will match any HTML file directly under
/people:@route('/people/<name>.html', 'GET') def get_person(request, name): person = db.lookup_person(name) return HTTPResponse(request, body=f'Hello, {person.name}!')
- class blinkenxmas.httpd.HTTPServer(server_address, RequestHandlerClass, bind_and_activate=True)[source]
The blinkenxmas HTTP server class, which descends from
http.server.ThreadingHTTPServerand is thus multi-threaded. This does precious little other than overridehandle_error().
- class blinkenxmas.httpd.HTTPRequestHandler(request, client_address, server)[source]
The blinkenxmas request handler. The
get_response()method is the primary piece of machinery that decides what handler deals with a given request. There are roughly three types of handler:Simple static data (included in the package data) is handled by
try_static()Chameleon templates (also included in the package data) are rendered by
try_template()Finally, custom functions (decorated by
route()) are called bytry_route()
- do_DELETE()[source]
Handle HTTP DELETE requests. See
get_response()for more information.
- do_GET()[source]
Handle HTTP GET requests. See
get_response()for more information.
- do_HEAD()[source]
Handle HTTP HEAD requests. See
get_response()for more information.
- do_POST()[source]
Handle HTTP POST requests. See
get_response()for more information.
- do_PUT()[source]
Handle HTTP PUT requests. See
get_response()for more information.
- get_response()[source]
Tries various methods (
try_route(),try_static(),try_template()in that order) to obtain aHTTPResponsefor the current request.Handles returning appropriate errors in the case of failure (500 internal server error in the case that rendering of a route or template fails, 404 not found in the case that no route, static file, or template can be found that matches the requested
path).
- get_template(name)[source]
Returns the Chameleon template with the specified name. Templates are loaded from module resources and cached in the
HTTPRequestHandler.template_cacheclass attribute.
- json()[source]
Decode the body of the request as a JSON object. Note this handler can be called once, and only once, as it reads the request body on-demand.
Warning
This method does not check the Content-Type header, and simply trusts that the request body is a valid JSON object. Wrap in exception handlers as appropriate!
- try_route()[source]
Searches for a match of the requested
pathin the definedroutes.If a match is found, the function associated with the route is called and, if it returns a
HTTPResponse, that is returned. If no match is found, returnsNone.
- try_static()[source]
Attempts to find a match for the requested
pathin the static data of the module.If a match is found, a
HTTPResponseis constructed and returned. Otherwise, returnsNone.
- try_template()[source]
Attempts to find a Chameleon template within the static data of the module that matches the requested
pathplus a.ptsuffix.If a template is found, it is rendered with the result of
get_template_ns()as the namespace, and aHTTPResponseis constructed from the result. Otherwise, returnsNone.
- class blinkenxmas.httpd.HTTPThread(config, messages, queue)[source]
The blinkenxmas HTTP thread class wraps an instance of
HTTPServerin aThreadfor background execution. Instances of this class may be used as a context manager that will start the thread upon entry, and stop it (re-raising any exception that occurred during execution) on exit. This is the recommended method of running this thread.- Parameters:
config (argparse.Namespace) – The application configuration
messages (Messages) – A buffer for messages to be relayed to the user
queue (queue.Queue) – The queue to submit animations to for transmission to the broker
Animation handlers
- blinkenxmas.httpd.animation(name, **params)[source]
Decorates a function as an animation generator to be presented in the Create interface. The doc-string of the function is used as the description and is expected to be in reStructuredText format (which will be rendered into HTML).
Each of the parameters to the function must be defined as a keyword argument to the decorator which is associated with one of the parameter classes defined:
- class blinkenxmas.httpd.Function(name, description, function, params)[source]
Defines an animation function.
- name
The short title of the animation.
- description
An extended description of the animation detailing all the parameters and the intended result. Typically derived from the function’s doc-string.
- function
The implementing callable function.
- class blinkenxmas.httpd.Param(label, input_type, *, default=None, min=None, max=None, choices=None, suffix=None)[source]
Defines the associated parameter as being a user-configured value.
The input_type is used in the generated
<input>element’s “type” parameter (if this is “select” then a<select>drop-down element is generated instead). The default, min, and max parameters correspond to the “default”, “min”, and “max” attributes of the<input>element. Finally, the choices parameter is a mapping of valid identifiers to labels used when input_type is “select”.- label
The content of the
<label>to render with the parameter’s<input>element.
- input_type
The value of the
<input>element’stypeparameter.
- default
The default value of the input.
- min
The minimum value for
rangetype inputs.
- max
The maximum value for
rangetype inputs.
- choices
A
dictdefining the valid selections forselecttype inputs. The values of the dictionary represent the labels for each option value.
- suffix
A text suffix to render after the input box.
- class blinkenxmas.httpd.ParamLEDCount[source]
Defines the associated parameter as taking the total number of LEDs on the tree (an
int).
- class blinkenxmas.httpd.ParamLEDPositions[source]
Defines the associated parameter as taking the mapping of LED indexes to
Positioninstances.Warning
Please be aware that not all LEDs may be included in the mapping. If an LED was not detected during calibration (either because it is persistently hidden or defective) then it will not be included in the mapping.
Support functions
- blinkenxmas.httpd.get_best_family(host, port)[source]
Given a host name and a port specification (either a number or a service name), returns the network family (e.g.
socket.AF_INET) and socket address to listen on as a tuple.
- blinkenxmas.httpd.for_commands(*commands)[source]
Decorator that associates methods in the request handler with HTTP commands like GET, HEAD, etc. This is only intended for internal use in
HTTPRequestHandler.
- class blinkenxmas.httpd.Messages(maxlen=20)[source]
This is a trivial class which is used to buffer up to maxlen messages, which are simple strings, for display to the user at some future point.
The
show()method is used to add a message to the buffer, anddrain()to retrieve all messages from the buffer as a list of strings. Instances of the class are thread-safe and may be used from multiple threads without additional locking.