API Reference

Core API

class microdot.Microdot

An HTTP application class.

This class implements an HTTP application instance and is heavily influenced by the Flask class of the Flask framework. It is typically declared near the start of the main application script.

Example:

from microdot import Microdot

app = Microdot()
route(url_pattern, methods=None)

Decorator that is used to register a function as a request handler for a given URL.

Parameters:
  • url_pattern – The URL pattern that will be compared against incoming requests.

  • methods – The list of HTTP methods to be handled by the decorated function. If omitted, only GET requests are handled.

The URL pattern can be a static path (for example, /users or /api/invoices/search) or a path with dynamic components enclosed in < and > (for example, /users/<id> or /invoices/<number>/products). Dynamic path components can also include a type prefix, separated from the name with a colon (for example, /users/<int:id>). The type can be string (the default), int, path or re:[regular-expression].

The first argument of the decorated function must be the request object. Any path arguments that are specified in the URL pattern are passed as keyword arguments. The return value of the function must be a Response instance, or the arguments to be passed to this class.

Example:

@app.route('/')
def index(request):
    return 'Hello, world!'
get(url_pattern)

Decorator that is used to register a function as a GET request handler for a given URL.

Parameters:

url_pattern – The URL pattern that will be compared against incoming requests.

This decorator can be used as an alias to the route decorator with methods=['GET'].

Example:

@app.get('/users/<int:id>')
def get_user(request, id):
    # ...
post(url_pattern)

Decorator that is used to register a function as a POST request handler for a given URL.

Parameters:

url_pattern – The URL pattern that will be compared against incoming requests.

This decorator can be used as an alias to the``route`` decorator with methods=['POST'].

Example:

@app.post('/users')
def create_user(request):
    # ...
put(url_pattern)

Decorator that is used to register a function as a PUT request handler for a given URL.

Parameters:

url_pattern – The URL pattern that will be compared against incoming requests.

This decorator can be used as an alias to the route decorator with methods=['PUT'].

Example:

@app.put('/users/<int:id>')
def edit_user(request, id):
    # ...
patch(url_pattern)

Decorator that is used to register a function as a PATCH request handler for a given URL.

Parameters:

url_pattern – The URL pattern that will be compared against incoming requests.

This decorator can be used as an alias to the route decorator with methods=['PATCH'].

Example:

@app.patch('/users/<int:id>')
def edit_user(request, id):
    # ...
delete(url_pattern)

Decorator that is used to register a function as a DELETE request handler for a given URL.

Parameters:

url_pattern – The URL pattern that will be compared against incoming requests.

This decorator can be used as an alias to the route decorator with methods=['DELETE'].

Example:

@app.delete('/users/<int:id>')
def delete_user(request, id):
    # ...
before_request(f)

Decorator to register a function to run before each request is handled. The decorated function must take a single argument, the request object.

Example:

@app.before_request
def func(request):
    # ...
after_request(f)

Decorator to register a function to run after each request is handled. The decorated function must take two arguments, the request and response objects. The return value of the function must be an updated response object.

Example:

@app.after_request
def func(request, response):
    # ...
    return response
after_error_request(f)

Decorator to register a function to run after an error response is generated. The decorated function must take two arguments, the request and response objects. The return value of the function must be an updated response object. The handler is invoked for error responses generated by Microdot, as well as those returned by application-defined error handlers.

Example:

@app.after_error_request
def func(request, response):
    # ...
    return response
errorhandler(status_code_or_exception_class)

Decorator to register a function as an error handler. Error handler functions for numeric HTTP status codes must accept a single argument, the request object. Error handler functions for Python exceptions must accept two arguments, the request object and the exception object.

Parameters:

status_code_or_exception_class – The numeric HTTP status code or Python exception class to handle.

Examples:

@app.errorhandler(404)
def not_found(request):
    return 'Not found'

@app.errorhandler(RuntimeError)
def runtime_error(request, exception):
    return 'Runtime error'
mount(subapp, url_prefix='')

Mount a sub-application, optionally under the given URL prefix.

Parameters:
  • subapp – The sub-application to mount.

  • url_prefix – The URL prefix to mount the application under.

static abort(status_code, reason=None)

Abort the current request and return an error response with the given status code.

Parameters:
  • status_code – The numeric status code of the response.

  • reason – The reason for the response, which is included in the response body.

Example:

from microdot import abort

@app.route('/users/<int:id>')
def get_user(id):
    user = get_user_by_id(id)
    if user is None:
        abort(404)
    return user.to_dict()
async start_server(host='0.0.0.0', port=5000, debug=False, ssl=None)

Start the Microdot web server as a coroutine. This coroutine does not normally return, as the server enters an endless listening loop. The shutdown() function provides a method for terminating the server gracefully.

Parameters:
  • host – The hostname or IP address of the network interface that will be listening for requests. A value of '0.0.0.0' (the default) indicates that the server should listen for requests on all the available interfaces, and a value of 127.0.0.1 indicates that the server should listen for requests only on the internal networking interface of the host.

  • port – The port number to listen for requests. The default is port 5000.

  • debug – If True, the server logs debugging information. The default is False.

  • ssl – An SSLContext instance or None if the server should not use TLS. The default is None.

This method is a coroutine.

Example:

import asyncio
from microdot import Microdot

app = Microdot()

@app.route('/')
async def index(request):
    return 'Hello, world!'

async def main():
    await app.start_server(debug=True)

asyncio.run(main())
run(host='0.0.0.0', port=5000, debug=False, ssl=None)

Start the web server. This function does not normally return, as the server enters an endless listening loop. The shutdown() function provides a method for terminating the server gracefully.

Parameters:
  • host – The hostname or IP address of the network interface that will be listening for requests. A value of '0.0.0.0' (the default) indicates that the server should listen for requests on all the available interfaces, and a value of 127.0.0.1 indicates that the server should listen for requests only on the internal networking interface of the host.

  • port – The port number to listen for requests. The default is port 5000.

  • debug – If True, the server logs debugging information. The default is False.

  • ssl – An SSLContext instance or None if the server should not use TLS. The default is None.

Example:

from microdot import Microdot

app = Microdot()

@app.route('/')
async def index(request):
    return 'Hello, world!'

app.run(debug=True)
shutdown()

Request a server shutdown. The server will then exit its request listening loop and the run() function will return. This function can be safely called from a route handler, as it only schedules the server to terminate as soon as the request completes.

Example:

@app.route('/shutdown')
def shutdown(request):
    request.app.shutdown()
    return 'The server is shutting down...'
class microdot.Request(app, client_addr, method, url, http_version, headers, body=None, stream=None, sock=None)

An HTTP request.

max_content_length = 16384

Specify the maximum payload size that is accepted. Requests with larger payloads will be rejected with a 413 status code. Applications can change this maximum as necessary.

Example:

Request.max_content_length = 1 * 1024 * 1024  # 1MB requests allowed
max_body_length = 16384

Specify the maximum payload size that can be stored in body. Requests with payloads that are larger than this size and up to max_content_length bytes will be accepted, but the application will only be able to access the body of the request by reading from stream. Set to 0 if you always access the body as a stream.

Example:

Request.max_body_length = 4 * 1024  # up to 4KB bodies read
max_readline = 2048

Specify the maximum length allowed for a line in the request. Requests with longer lines will not be correctly interpreted. Applications can change this maximum as necessary.

Example:

Request.max_readline = 16 * 1024  # 16KB lines allowed
app

The application instance to which this request belongs.

client_addr

The address of the client, as a tuple (host, port).

method

The HTTP method of the request.

url

The request URL, including the path and query string.

headers

A dictionary with the headers included in the request.

cookies

A dictionary with the cookies included in the request.

g

A general purpose container for applications to store data during the life of the request.

path

The path portion of the URL.

query_string

The query string portion of the URL.

args

The parsed query string, as a MultiDict object.

content_length

The parsed Content-Length header.

content_type

The parsed Content-Type header.

async static create(app, client_reader, client_writer, client_addr)

Create a request object.

Parameters:
  • app – The Microdot application instance.

  • client_reader – An input stream from where the request data can be read.

  • client_writer – An output stream where the response data can be written.

  • client_addr – The address of the client, as a tuple.

This method is a coroutine. It returns a newly created Request object.

property body

The body of the request, as bytes.

property stream

The body of the request, as a bytes stream.

property json

The parsed JSON body, or None if the request does not have a JSON body.

property form

The parsed form submission body, as a MultiDict object, or None if the request does not have a form submission.

after_request(f)

Register a request-specific function to run after the request is handled. Request-specific after request handlers run at the very end, after the application’s own after request handlers. The function must take two arguments, the request and response objects. The return value of the function must be the updated response object.

Example:

@app.route('/')
def index(request):
    # register a request-specific after request handler
    @req.after_request
    def func(request, response):
        # ...
        return response

    return 'Hello, World!'

Note that the function is not called if the request handler raises an exception and an error response is returned instead.

class microdot.Response(body='', status_code=200, headers=None, reason=None)

An HTTP response class.

Parameters:
  • body – The body of the response. If a dictionary or list is given, a JSON formatter is used to generate the body. If a file-like object or an async generator is given, a streaming response is used. If a string is given, it is encoded from UTF-8. Else, the body should be a byte sequence.

  • status_code – The numeric HTTP status code of the response. The default is 200.

  • headers – A dictionary of headers to include in the response.

  • reason – A custom reason phrase to add after the status code. The default is “OK” for responses with a 200 status code and “N/A” for any other status codes.

default_content_type = 'text/plain'

The content type to use for responses that do not explicitly define a Content-Type header.

default_send_file_max_age = None

The default cache control max age used by send_file(). A value of None means that no Cache-Control header is added.

already_handled = <microdot.microdot.Response object>

Special response used to signal that a response does not need to be written to the client. Used to exit WebSocket connections cleanly.

Add a cookie to the response.

Parameters:
  • cookie – The cookie’s name.

  • value – The cookie’s value.

  • path – The cookie’s path.

  • domain – The cookie’s domain.

  • expires – The cookie expiration time, as a datetime object or a correctly formatted string.

  • max_age – The cookie’s Max-Age value.

  • secure – The cookie’s secure flag.

  • http_only – The cookie’s HttpOnly flag.

  • partitioned – Whether the cookie is partitioned.

Delete a cookie.

Parameters:
  • cookie – The cookie’s name.

  • kwargs – Any cookie opens and flags supported by set_cookie() except expires and max_age.

classmethod redirect(location, status_code=302)

Return a redirect response.

Parameters:
  • location – The URL to redirect to.

  • status_code – The 3xx status code to use for the redirect. The default is 302.

classmethod send_file(filename, status_code=200, content_type=None, stream=None, max_age=None, compressed=False, file_extension='')

Send file contents in a response.

Parameters:
  • filename – The filename of the file.

  • status_code – The 3xx status code to use for the redirect. The default is 302.

  • content_type – The Content-Type header to use in the response. If omitted, it is generated automatically from the file extension of the filename parameter.

  • stream – A file-like object to read the file contents from. If a stream is given, the filename parameter is only used when generating the Content-Type header.

  • max_age – The Cache-Control header’s max-age value in seconds. If omitted, the value of the Response.default_send_file_max_age attribute is used.

  • compressed – Whether the file is compressed. If True, the Content-Encoding header is set to gzip. A string with the header value can also be passed. Note that when using this option the file must have been compressed beforehand. This option only sets the header.

  • file_extension – A file extension to append to the filename parameter when opening the file, including the dot. The extension given here is not considered when generating the Content-Type header.

Security note: The filename is assumed to be trusted. Never pass filenames provided by the user without validating and sanitizing them first.

WebSocket

exception microdot.websocket.WebSocketError

Exception raised when an error occurs in a WebSocket connection.

class microdot.websocket.WebSocket(request)

A WebSocket connection object.

An instance of this class is sent to handler functions to manage the WebSocket connection.

max_message_length = -1

Specify the maximum message size that can be received when calling the receive() method. Messages with payloads that are larger than this size will be rejected and the connection closed. Set to 0 to disable the size check (be aware of potential security issues if you do this), or to -1 to use the value set in Request.max_body_length. The default is -1.

Example:

WebSocket.max_message_length = 4 * 1024  # up to 4KB messages
async receive()

Receive a message from the client.

async send(data, opcode=None)

Send a message to the client.

Parameters:
  • data – the data to send, given as a string or bytes.

  • opcode – a custom frame opcode to use. If not given, the opcode is TEXT or BINARY depending on the type of the data.

async close()

Close the websocket connection.

async microdot.websocket.websocket_upgrade(request)

Upgrade a request handler to a websocket connection.

This function can be called directly inside a route function to process a WebSocket upgrade handshake, for example after the user’s credentials are verified. The function returns the websocket object:

@app.route('/echo')
async def echo(request):
    if not authenticate_user(request):
        abort(401)
    ws = await websocket_upgrade(request)
    while True:
        message = await ws.receive()
        await ws.send(message)
microdot.websocket.with_websocket(f)

Decorator to make a route a WebSocket endpoint.

This decorator is used to define a route that accepts websocket connections. The route then receives a websocket object as a second argument that it can use to send and receive messages:

@app.route('/echo')
@with_websocket
async def echo(request, ws):
    while True:
        message = await ws.receive()
        await ws.send(message)

Server-Sent Events (SSE)

class microdot.sse.SSE

Server-Sent Events object.

An object of this class is sent to handler functions to manage the SSE connection.

async send(data, event=None, event_id=None)

Send an event to the client.

Parameters:
  • data – the data to send. It can be given as a string, bytes, dict or list. Dictionaries and lists are serialized to JSON. Any other types are converted to string before sending.

  • event – an optional event name, to send along with the data. If given, it must be a string.

  • event_id – an optional event id, to send along with the data. If given, it must be a string.

microdot.sse.sse_response(request, event_function, *args, **kwargs)

Return a response object that initiates an event stream.

Parameters:
  • request – the request object.

  • event_function – an asynchronous function that will send events to the client. The function is invoked with request and an sse object. The function should use sse.send() to send events to the client.

  • args – additional positional arguments to be passed to the response.

  • kwargs – additional keyword arguments to be passed to the response.

This is a low-level function that can be used to implement a custom SSE endpoint. In general the microdot.sse.with_sse() decorator should be used instead.

microdot.sse.with_sse(f)

Decorator to make a route a Server-Sent Events endpoint.

This decorator is used to define a route that accepts SSE connections. The route then receives a sse object as a second argument that it can use to send events to the client:

@app.route('/events')
@with_sse
async def events(request, sse):
    # send an unnamed event with string data
    await sse.send('hello')

    # send an unnamed event with JSON data
    await sse.send({'foo': 'bar'})

    # send a named event
    await sse.send('hello', event='greeting')

Templates (uTemplate)

class microdot.utemplate.Template(template)

A template object.

Parameters:

template – The filename of the template to render, relative to the configured template directory.

classmethod initialize(template_dir='templates', loader_class=<class 'utemplate.recompile.Loader'>)

Initialize the templating subsystem.

Parameters:
  • template_dir – the directory where templates are stored. This argument is optional. The default is to load templates from a templates subdirectory.

  • loader_class – the utemplate.Loader class to use when loading templates. This argument is optional. The default is the recompile.Loader class, which automatically recompiles templates when they change.

name

The name of the template

generate(*args, **kwargs)

Return a generator that renders the template in chunks, with the given arguments.

render(*args, **kwargs)

Render the template with the given arguments and return it as a string.

generate_async(*args, **kwargs)

Return an asynchronous generator that renders the template in chunks, using the given arguments.

async render_async(*args, **kwargs)

Render the template with the given arguments asynchronously and return it as a string.

Templates (Jinja)

class microdot.jinja.Template(template)

A template object.

Parameters:

template – The filename of the template to render, relative to the configured template directory.

classmethod initialize(template_dir='templates', enable_async=False, **kwargs)

Initialize the templating subsystem.

Parameters:
  • template_dir – the directory where templates are stored. This argument is optional. The default is to load templates from a templates subdirectory.

  • enable_async – set to True to enable the async rendering engine in Jinja, and the render_async() and generate_async() methods.

  • kwargs – any additional options to be passed to Jinja’s Environment class.

name

The name of the template

generate(*args, **kwargs)

Return a generator that renders the template in chunks, with the given arguments.

render(*args, **kwargs)

Render the template with the given arguments and return it as a string.

generate_async(*args, **kwargs)

Return an asynchronous generator that renders the template in chunks, using the given arguments.

async render_async(*args, **kwargs)

Render the template with the given arguments asynchronously and return it as a string.

User Sessions

class microdot.session.SessionDict(request, session_dict)

A session dictionary.

The session dictionary is a standard Python dictionary that has been extended with convenience save() and delete() methods.

save()

Update the session cookie.

delete()

Delete the session cookie.

class microdot.session.Session(app=None, secret_key=None)
Parameters:
  • app – The application instance.

  • key – The secret key, as a string or bytes object.

get(request)

Retrieve the user session.

Parameters:

request – The client request.

The return value is a session dictionary with the data stored in the user’s session, or {} if the session data is not available or invalid.

update(request, session)

Update the user session.

Parameters:
  • request – The client request.

  • session – A dictionary with the update session data for the user.

Applications would normally not call this method directly, instead they would use the SessionDict.save() method on the session dictionary, which calls this method. For example:

@app.route('/')
@with_session
def index(request, session):
    session['foo'] = 'bar'
    session.save()
    return 'Hello, World!'

Calling this method adds a cookie with the updated session to the request currently being processed.

delete(request)

Remove the user session.

Parameters:

request – The client request.

Applications would normally not call this method directly, instead they would use the SessionDict.delete() method on the session dictionary, which calls this method. For example:

@app.route('/')
@with_session
def index(request, session):
    session.delete()
    return 'Hello, World!'

Calling this method adds a cookie removal header to the request currently being processed.

microdot.session.with_session(f)

Decorator that passes the user session to the route handler.

The session dictionary is passed to the decorated function as an argument after the request object. Example:

@app.route('/')
@with_session
def index(request, session):
    return 'Hello, World!'

Note that the decorator does not save the session. To update the session, call the session.save() method.

Cross-Origin Resource Sharing (CORS)

class microdot.cors.CORS(app=None, allowed_origins=None, allow_credentials=False, allowed_methods=None, expose_headers=None, allowed_headers=None, max_age=None, handle_cors=True)

Add CORS headers to HTTP responses.

Parameters:
  • app – The application to add CORS headers to.

  • allowed_origins – A list of origins that are allowed to make cross-site requests. If set to ‘*’, all origins are allowed.

  • allow_credentials – If set to True, the Access-Control-Allow-Credentials header will be set to true to indicate to the browser that it can expose cookies and authentication headers.

  • allowed_methods – A list of methods that are allowed to be used when making cross-site requests. If not set, all methods are allowed.

  • expose_headers – A list of headers that the browser is allowed to exposed.

  • allowed_headers – A list of headers that are allowed to be used when making cross-site requests. If not set, all headers are allowed.

  • max_age – The maximum amount of time in seconds that the browser should cache the results of a preflight request.

  • handle_cors – If set to False, CORS headers will not be added to responses. This can be useful if you want to add CORS headers manually.

initialize(app, handle_cors=True)

Initialize the CORS object for the given application.

Parameters:
  • app – The application to add CORS headers to.

  • handle_cors – If set to False, CORS headers will not be added to responses. This can be useful if you want to add CORS headers manually.

get_cors_headers(request)

Return a dictionary of CORS headers to add to a given request.

Parameters:

request – The request to add CORS headers to.

Test Client

class microdot.test_client.TestClient(app, cookies=None)

A test client for Microdot.

Parameters:
  • app – The Microdot application instance.

  • cookies – A dictionary of cookies to use when sending requests to the application.

The following example shows how to create a test client for an application and send a test request:

from microdot import Microdot

app = Microdot()

@app.get('/')
async def index():
    return 'Hello, World!'

async def test_hello_world(self):
    client = TestClient(app)
    res = await client.get('/')
    assert res.status_code == 200
    assert res.text == 'Hello, World!'
async get(path, headers=None)

Send a GET request to the application.

Parameters:
  • path – The request URL.

  • headers – A dictionary of headers to send with the request.

This method returns a TestResponse object.

async post(path, headers=None, body=None)

Send a POST request to the application.

Parameters:
  • path – The request URL.

  • headers – A dictionary of headers to send with the request.

  • body – The request body. If a dictionary or list is provided, a JSON-encoded body will be sent. A string body is encoded to bytes as UTF-8. A bytes body is sent as-is.

This method returns a TestResponse object.

async put(path, headers=None, body=None)

Send a PUT request to the application.

Parameters:
  • path – The request URL.

  • headers – A dictionary of headers to send with the request.

  • body – The request body. If a dictionary or list is provided, a JSON-encoded body will be sent. A string body is encoded to bytes as UTF-8. A bytes body is sent as-is.

This method returns a TestResponse object.

async patch(path, headers=None, body=None)

Send a PATCH request to the application.

Parameters:
  • path – The request URL.

  • headers – A dictionary of headers to send with the request.

  • body – The request body. If a dictionary or list is provided, a JSON-encoded body will be sent. A string body is encoded to bytes as UTF-8. A bytes body is sent as-is.

This method returns a TestResponse object.

async delete(path, headers=None)

Send a DELETE request to the application.

Parameters:
  • path – The request URL.

  • headers – A dictionary of headers to send with the request.

This method returns a TestResponse object.

async websocket(path, client, headers=None)

Send a websocket connection request to the application.

Parameters:
  • path – The request URL.

  • client – A generator function that yields client messages.

  • headers – A dictionary of headers to send with the request.

class microdot.test_client.TestResponse

A response object issued by the Microdot test client.

status_code

The numeric status code returned by the server.

reason

The text reason associated with the status response, such as 'OK' or 'NOT FOUND'. Set to None unless the application explicitly sets it on the response object.

headers

A dictionary with the response headers.

body

The body of the response, as a bytes object.

text

The body of the response, decoded to a UTF-8 string. Set to None if the response cannot be represented as UTF-8 text.

json

The body of the JSON response, decoded to a dictionary or list. Set Note if the response does not have a JSON payload.

ASGI

class microdot.asgi.Microdot

A subclass of the core Microdot class that implements the ASGI protocol.

This class must be used as the application instance when running under an ASGI web server.

async asgi_app(scope, receive, send)

An ASGI application.

WSGI

class microdot.wsgi.Microdot

A subclass of the core Microdot class that implements the WSGI protocol.

This class must be used as the application instance when running under a WSGI web server.

wsgi_app(environ, start_response)

A WSGI application callable.