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='', local=False)

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.

  • local – When set to True, the before, after and error request handlers only apply to endpoints defined in the sub-application. When False, they apply to the entire application. The default is False.

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_serving=True)

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.

  • start_serving – If True, the server starts accepting connections immediately. When set to False, this method returns a Server object. To accept connections, the Server.serve_forever() method should be called. The default is True. A value of False is only supported in CPython.

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, url_prefix='', subapp=None, scheme=None, route=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.

scheme

The scheme of the request, either http or https.

url

The request URL, including the path and query string, but not the scheme or the host, which is available in the Host header.

url_prefix

The URL prefix, if the endpoint comes from a mounted sub-application, or else ‘’.

subapp

The sub-application instance, or None if this isn’t a mounted endpoint.

route

The route function that handles this request.

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, scheme=None)

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.

  • scheme – The scheme of the request, either ‘http’ or ‘https’.

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.

Forms that are URL encoded are processed by default. For multipart forms to be processed, the with_form_data decorator must be added to the route.

property files

The files uploaded in the request as a dictionary, or None if the request does not have any files.

The with_form_data decorator must be added to the route that receives file uploads for this property to be set.

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=b'', 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 options and flags supported by set_cookie(). Values given for expires and max_age are ignored.

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 200.

  • 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.

class microdot.URLPattern(url_pattern)

A class that represents the URL pattern for a route.

Parameters:

url_pattern – The route URL pattern, which can include static and dynamic path segments. Dynamic segments are enclosed in < and >. The type of the segment can be given as a prefix, separated from the name with a colon. Supported types are string (the default), int and path. Custom types can be registered using the URLPattern.register_type() method.

classmethod register_type(type_name, pattern='[^/]+', parser=None)

Register a new URL segment type.

Parameters:
  • type_name – The name of the segment type to register.

  • pattern – The regular expression pattern to use when matching this segment type. If not given, a default matcher for a single path segment is used.

  • parser – A callable that will be used to parse and transform the value of the segment. If omitted, the value is returned as a string.

compile()

Generate a regular expression for the URL pattern.

This method is automatically invoked the first time the URL pattern is matched against a path.

match(path)

Match a path against the URL pattern.

Returns a dictionary with the values of all dynamic path segments if a matche is found, or None if the path does not match this pattern.