webapi ====== .. py:module:: webapi .. autoapi-nested-parse:: Tiny HTTP server for the board: JSON API and the settings page. Attributes ---------- .. autoapisummary:: webapi.MAX_REQUEST webapi.WAIT_SLICE_S webapi.JSON webapi.HTML Classes ------- .. autoapisummary:: webapi.Server Functions --------- .. autoapisummary:: webapi.reply webapi.page webapi.response_for webapi.read_request webapi.headers_of webapi.handle webapi.serve Module Contents --------------- .. py:data:: MAX_REQUEST :value: 16384 .. py:data:: WAIT_SLICE_S :value: 0.2 .. py:data:: JSON :value: 'application/json' .. py:data:: HTML :value: 'text/html; charset=utf-8' .. py:function:: reply(payload, status='200 OK') A JSON response, for handlers that need a status other than 200. .. py:function:: page(html) An HTML response. .. py:function:: 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. .. py:function:: 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`. .. py:function:: headers_of(head) Request headers as {lowercase name: value}. .. py:function:: 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`. .. py:class:: 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. .. py:attribute:: routes .. py:attribute:: raw_routes :value: None .. py:attribute:: socket .. py:method:: poll(timeout_s) Answer requests for about `timeout_s` seconds. .. py:method:: close() Stop listening. .. py:function:: serve(routes, port=80, duration_s=None) Answer requests forever, or for about `duration_s` seconds. See `response_for` for `routes`.