adafruit_httpserver

Simple HTTP Server for CircuitPython

  • Author(s): Dan Halbert

Implementation Notes

Software and Dependencies:

class adafruit_httpserver.HTTPResponse(*, status: tuple = HTTPStatus.OK, content_type: str = MIMEType.TEXT_PLAIN, body: str = '', filename: Optional[str] = None, root: str = '')

Details of an HTTP response. Use in @`HTTPServer.route` decorator functions.

Create an HTTP response.

Parameters
  • status (tuple) – The HTTP status code to return, as a tuple of (int, “message”). Common statuses are available in HTTPStatus.

  • content_type (str) – The MIME type of the data being returned. Common MIME types are available in MIMEType.

  • body (Union[str|bytes]) – The data to return in the response body, if filename is not None.

  • filename (str) – If not None, return the contents of the specified file, and ignore body.

  • root (str) – root directory for filename, without a trailing slash

send(conn: Any) None

Send the constructed response over the given socket.

class adafruit_httpserver.HTTPServer(socket_source: Any)

A basic socket-based HTTP server.

Create a server, and get it ready to run.

Parameters

socket – An object that is a source of sockets. This could be a socketpool in CircuitPython or the socket module in CPython.

poll()

Call this method inside your main event loop to get the server to check for new incoming client requests. When a request comes in, the application callable will be invoked.

route(path: str, method: str = 'GET')

Decorator used to add a route.

Parameters
  • path (str) – filename path

  • method (str) – HTTP method: “GET”, “POST”, etc.

Example:

@server.route(path, method)
def route_func(request):
    return HTTPResponse(body="hello world")
serve_forever(host: str, port: int = 80, root: str = '') None

Wait for HTTP requests at the given host and port. Does not return.

Parameters
  • host (str) – host name or IP address

  • port (int) – port

  • root (str) – root directory to serve files from

start(host: str, port: int = 80, root: str = '') None

Start the HTTP server at the given host and port. Requires calling poll() in a while loop to handle incoming requests.

Parameters
  • host (str) – host name or IP address

  • port (int) – port

  • root (str) – root directory to serve files from

class adafruit_httpserver.HTTPStatus(value, phrase)

HTTP status codes.

Define a status code.

Parameters
  • value (int) – Numeric value: 200, 404, etc.

  • phrase (str) – Short phrase: “OK”, “Not Found’, etc.

class adafruit_httpserver.MIMEType

Common MIME types. From https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

static mime_type(filename)

Return the mime type for the given filename. If not known, return “text/plain”.