webapi

Tiny HTTP server for the board: JSON API and the settings page.

Attributes

Classes

Server

Non-blocking HTTP server.

Functions

reply(payload[, status])

A JSON response, for handlers that need a status other than 200.

page(html)

An HTML response.

response_for(request, routes)

Build the raw HTTP response for a raw HTTP request (bytes).

read_request(recv[, max_size])

Read one request with recv(n).

headers_of(head)

Request headers as {lowercase name: value}.

handle(recv, routes[, raw_routes, max_size])

Read one request with recv(n) and return the raw response.

serve(routes[, port, duration_s])

Answer requests forever, or for about duration_s seconds.

Module Contents

webapi.MAX_REQUEST = 16384
webapi.WAIT_SLICE_S = 0.2
webapi.JSON = 'application/json'
webapi.HTML = 'text/html; charset=utf-8'
webapi.reply(payload, status='200 OK')

A JSON response, for handlers that need a status other than 200.

webapi.page(html)

An HTML response.

webapi.response_for(request, routes)

Build the raw HTTP response for a raw HTTP request (bytes).

routes maps “METHOD /path” to handlers. GET handlers take no arguments, POST handlers the request body (bytes). A handler returns a JSON-serialisable payload, or a (status, content type, body) tuple as reply() and page() build it. Exceptions become a 500 response.

webapi.read_request(recv, max_size=MAX_REQUEST)

Read one request with recv(n).

Reads the headers and the body as long as Content-Length announces.

Raises:

ValueError – If the request exceeds max_size.

webapi.headers_of(head)

Request headers as {lowercase name: value}.

webapi.handle(recv, routes, raw_routes=None, max_size=MAX_REQUEST)

Read one request with recv(n) and return the raw response.

routes are served by response_for. raw_routes map “METHOD /prefix” to handlers for requests that need their headers or a large body (file uploads): handler(rest of the path, headers, Content-Length, body chunks) returns what a normal handler returns. They are matched by prefix before routes; the body is streamed, not limited by max_size.

class webapi.Server(routes, port=80, raw_routes=None)

Non-blocking HTTP server.

poll answers requests for a while, so the caller can do other work in between.

routes
raw_routes = None
socket
poll(timeout_s)

Answer requests for about timeout_s seconds.

close()

Stop listening.

webapi.serve(routes, port=80, duration_s=None)

Answer requests forever, or for about duration_s seconds.

See response_for for routes.