API Reference¶
Core API¶
- class microdot.Microdot¶
An HTTP application class.
This class implements an HTTP application instance and is heavily influenced by the
Flaskclass 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
GETrequests are handled.
The URL pattern can be a static path (for example,
/usersor/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 bestring(the default),int,pathorre:[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
Responseinstance, 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
GETrequest 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
routedecorator withmethods=['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
POSTrequest 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
PUTrequest 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
routedecorator withmethods=['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
PATCHrequest 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
routedecorator withmethods=['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
DELETErequest 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
routedecorator withmethods=['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. WhenFalse, they apply to the entire application. The default isFalse.
- 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 of127.0.0.1indicates 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 isFalse.ssl – An
SSLContextinstance orNoneif the server should not use TLS. The default isNone.
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 of127.0.0.1indicates 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 isFalse.ssl – An
SSLContextinstance orNoneif the server should not use TLS. The default isNone.
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)¶
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 tomax_content_lengthbytes will be accepted, but the application will only be able to access the body of the request by reading fromstream. 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.
- 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.
- 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
MultiDictobject.
- content_length¶
The parsed
Content-Lengthheader.
- content_type¶
The parsed
Content-Typeheader.
- 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
Requestobject.
- 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
Noneif the request does not have a JSON body.
- property form¶
The parsed form submission body, as a
MultiDictobject, orNoneif 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_datadecorator must be added to the route.
- property files¶
The files uploaded in the request as a dictionary, or
Noneif the request does not have any files.The
with_form_datadecorator 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='', 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-Typeheader.
- default_send_file_max_age = None¶
The default cache control max age used by
send_file(). A value ofNonemeans that noCache-Controlheader 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.
- set_cookie(cookie, value, path=None, domain=None, expires=None, max_age=None, secure=False, http_only=False, partitioned=False)¶
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
datetimeobject or a correctly formatted string.max_age – The cookie’s
Max-Agevalue.secure – The cookie’s
secureflag.http_only – The cookie’s
HttpOnlyflag.partitioned – Whether the cookie is partitioned.
- delete_cookie(cookie, **kwargs)¶
Delete a cookie.
- Parameters:
cookie – The cookie’s name.
kwargs – Any cookie opens and flags supported by
set_cookie()exceptexpiresandmax_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-Typeheader to use in the response. If omitted, it is generated automatically from the file extension of thefilenameparameter.stream – A file-like object to read the file contents from. If a stream is given, the
filenameparameter is only used when generating theContent-Typeheader.max_age – The
Cache-Controlheader’smax-agevalue in seconds. If omitted, the value of theResponse.default_send_file_max_ageattribute is used.compressed – Whether the file is compressed. If
True, theContent-Encodingheader is set togzip. 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
filenameparameter when opening the file, including the dot. The extension given here is not considered when generating theContent-Typeheader.
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 arestring(the default),intandpath. Custom types can be registered using theURLPattern.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
Noneif the path does not match this pattern.
Multipart Forms¶
- class microdot.multipart.FormDataIter(request)¶
Asynchronous iterator that parses a
multipart/form-databody and returns form fields and files as they are parsed.- Parameters:
request – the request object to parse.
Example usage:
from microdot.multipart import FormDataIter @app.post('/upload') async def upload(request): async for name, value in FormDataIter(request): print(name, value)
The iterator returns no values when the request has a content type other than
multipart/form-data. For a file field, the returned value is of typeFileUpload, which supports theread()andsave()methods. Values for regular fields are provided as strings.The request body is read efficiently in chunks of size
buffer_size. On iterations in which a file field is encountered, the file must be consumed before moving on to the next iteration, as the internal stream stored inFileUploadinstances is invalidated at the end of the iteration.- buffer_size = 256¶
The size of the buffer used to read chunks of the request body.
- class microdot.multipart.FileUpload(filename, content_type, read)¶
Class that represents an uploaded file.
- Parameters:
filename – the name of the uploaded file.
content_type – the content type of the uploaded file.
read – a coroutine that reads from the uploaded file’s stream.
An uploaded file can be read from the stream using the
read()method or saved to a file using thesave()method.Instances of this class do not normally need to be created directly.
- max_memory_size = 1024¶
The size at which the file is copied to a temporary file.
- async read(n=-1)¶
Read up to
nbytes from the uploaded file’s stream.- Parameters:
n – the maximum number of bytes to read. If
nis -1 or not given, the entire file is read.
- async save(path_or_file)¶
Save the uploaded file to the given path or file object.
- Parameters:
path_or_file – the path to save the file to, or a file object to which the file is to be written.
The file is read and written in chunks of size
FormDataIter.buffer_size.
- async copy(max_memory_size=None)¶
Copy the uploaded file to a temporary file, to allow the parsing of the multipart form to continue.
- Parameters:
max_memory_size – the maximum size of the file to keep in memory. If not given, then the class attribute of the same name is used.
- async close()¶
Close an open file.
This method must be called to free memory or temporary files created by the
copy()method.Note that when using the
@with_form_datadecorator this method is called automatically when the request ends.
- microdot.multipart.with_form_data(f)¶
Decorator that parses a
multipart/form-databody and updates the request object with the parsed form fields and files.Example usage:
from microdot.multipart import with_form_data @app.post('/upload') @with_form_data async def upload(request): print('form fields:', request.form) print('files:', request.files)
Note: this decorator calls the
FileUpload.copy()method on all uploaded files, so that the request can be parsed in its entirety. The files are either copied to memory or a temporary file, depending on their size. The temporary files are automatically deleted when the request ends.
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 inRequest.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
TEXTorBINARYdepending 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
requestand ansseobject. The function should usesse.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.Loaderclass to use when loading templates. This argument is optional. The default is therecompile.Loaderclass, 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, **kwargs)¶
A template object.
- Parameters:
template – The filename of the template to render, relative to the configured template directory.
kwargs – any additional options to be passed to the Jinja environment’s
get_template()method.
- jinja_env = None¶
The Jinja environment. The
initialize()method must be called before this attribute is accessed.
- classmethod initialize(template_dir='templates', enable_async=False, **kwargs)¶
Initialize the templating subsystem.
This method is automatically invoked when the first template is created. The application can call it explicitly if custom options need to be provided.
- 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
Trueto enable the async rendering engine in Jinja, and therender_async()andgenerate_async()methods.kwargs – any additional options to be passed to Jinja’s
Environmentclass.
- 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()anddelete()methods.- save()¶
Update the session cookie.
- delete()¶
Delete the session cookie.
- class microdot.session.Session(app=None, secret_key=None, cookie_options=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.
Authentication¶
- class microdot.auth.BasicAuth(realm='Please login', charset='UTF-8', scheme='Basic', error_status=401)¶
Basic Authentication.
- Parameters:
realm – The realm that is displayed when the user is prompted to authenticate in the browser.
charset – The charset that is used to encode the realm.
scheme – The authentication scheme. Defaults to ‘Basic’.
error_status – The error status code to return when authentication fails. Defaults to 401.
- authenticate(f)¶
Decorator to configure the authentication callback.
This decorator must be used with a function that accepts the request object, a username and a password and returns a user object if the credentials are valid, or
Noneif they are not. Example:@auth.authenticate async def check_credentials(request, username, password): user = get_user(username) if user and user.check_password(password): return get_user(username)
- __call__(f)¶
Decorator to protect a route with authentication.
An instance of this class must be used as a decorator on the routes that need to be protected. Example:
auth = BasicAuth() # or TokenAuth() @app.route('/protected') @auth def protected(request): # ...
Routes that are decorated in this way will only be invoked if the authentication callback returned a valid user object, otherwise the error callback will be executed.
- optional(f)¶
Decorator to protect a route with optional authentication.
This decorator makes authentication for the decorated route optional, meaning that the route is allowed to run with or with authentication given in the request.
- class microdot.auth.TokenAuth(header='Authorization', scheme='Bearer', error_status=401)¶
Token based authentication.
- Parameters:
header – The name of the header that will contain the token. Defaults to ‘Authorization’.
scheme – The authentication scheme. Defaults to ‘Bearer’.
error_status – The error status code to return when authentication fails. Defaults to 401.
- authenticate(f)¶
Decorator to configure the authentication callback.
This decorator must be used with a function that accepts the request object, a username and a password and returns a user object if the credentials are valid, or
Noneif they are not. Example:@auth.authenticate async def check_credentials(request, token): return get_user(token)
- errorhandler(f)¶
Decorator to configure the error callback.
Microdot calls the error callback to allow the application to generate a custom error response. The default error response is to call
abort(401).
- __call__(f)¶
Decorator to protect a route with authentication.
An instance of this class must be used as a decorator on the routes that need to be protected. Example:
auth = BasicAuth() # or TokenAuth() @app.route('/protected') @auth def protected(request): # ...
Routes that are decorated in this way will only be invoked if the authentication callback returned a valid user object, otherwise the error callback will be executed.
- optional(f)¶
Decorator to protect a route with optional authentication.
This decorator makes authentication for the decorated route optional, meaning that the route is allowed to run with or with authentication given in the request.
User Logins¶
- class microdot.login.Login(login_url='/login')¶
User login support for Microdot.
- Parameters:
login_url – the URL to redirect to when a login is required. The default is ‘/login’.
- user_loader(f)¶
Decorator to configure the user callback.
The decorated function receives the user ID as an argument and must return the corresponding user object, or
Noneif the user ID is invalid.
- async login_user(request, user, remember=False, redirect_url='/')¶
Log a user in.
- Parameters:
request – the request object
user – the user object
remember – if the user’s logged in state should be remembered with a cookie after the session ends. Set to the number of days the remember cookie should last, or to
Trueto use a default duration of 30 days.redirect_url – the URL to redirect to after login
This call marks the user as logged in by storing their user ID in the user session. The application must call this method to log a user in after their credentials have been validated.
The method returns a redirect response, either to the URL the user originally intended to visit, or if there is no original URL to the URL specified by the redirect_url.
- async logout_user(request)¶
Log a user out.
- Parameters:
request – the request object
This call removes information about the user’s log in from the user session. If a remember cookie exists, it is removed as well.
- __call__(f)¶
Decorator to protect a route with authentication.
If the user is not logged in, Microdot will redirect to the login page first. The decorated route will only run after successful login by the user. If the user is already logged in, the route will run immediately. Example:
login = Login() @app.route('/secret') @login async def secret(request): # only accessible to authenticated users
- fresh(f)¶
Decorator to protect a route with “fresh” authentication.
This decorator prevents the route from running when the login session is not fresh. A fresh session is a session that has been created from direct user interaction with the login page, while a non-fresh session occurs when a login is restored from a “remember me” cookie. Example:
login = Login() @app.route('/secret') @auth.fresh async def secret(request): # only accessible to authenticated users # users logged in via remember me cookie will need to # re-authenticate
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-Credentialsheader will be set totrueto 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
TestResponseobject.
- 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
TestResponseobject.
- 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
TestResponseobject.
- 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
TestResponseobject.
- 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
TestResponseobject.
- 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 toNoneunless 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
Noneif the response cannot be represented as UTF-8 text.
- json¶
The body of the JSON response, decoded to a dictionary or list. Set
Noteif the response does not have a JSON payload.
- events¶
The body of the SSE response, decoded to a list of events, each given as a dictionary with a
datakey and optionally alsoeventandidkeys. Set toNoneif the response does not have an SSE payload.