API Reference¶
microdot
module¶
- 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 bestring
(the default),int
,path
orre:[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 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
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 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
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 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
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 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='')¶
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()
- 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.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 isFalse
.ssl – An
SSLContext
instance orNone
if the server should not use TLS. The default isNone
.
Example:
from microdot import Microdot app = Microdot() @app.route('/') 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 tomax_content_length
bytes 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
- socket_read_timeout = 1¶
Specify a suggested read timeout to use when reading the request. Set to 0 to disable the use of a timeout. This timeout should be considered a suggestion only, as some platforms may not support it. The default is 1 second.
- 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.
- content_length¶
The parsed
Content-Length
header.
- content_type¶
The parsed
Content-Type
header.
- static create(app, client_stream, client_addr, client_sock=None)¶
Create a request object.
- Parameters:
app – The Microdot application instance.
client_stream – An input stream from where the request data can be read.
client_addr – The address of the client, as a tuple.
client_sock – The low-level socket associated with the request.
This method returns a newly created
Request
object.
- property body¶
The body of the request, as bytes.
- property stream¶
The input stream, containing the request body.
- 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, orNone
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 a 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 ofNone
means that noCache-Control
header is added.
- already_handled = <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)¶
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.
- 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 thefilename
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 theContent-Type
header.max_age – The
Cache-Control
header’smax-age
value in seconds. If omitted, the value of theResponse.default_send_file_max_age
attribute is used.compressed – Whether the file is compressed. If
True
, theContent-Encoding
header 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
filename
parameter when opening the file, including the dot. The extension given here is not considered when generating theContent-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.NoCaseDict(initial_dict=None)¶
A subclass of dictionary that holds case-insensitive keys.
- Parameters:
initial_dict – an initial dictionary of key/value pairs to initialize this object with.
Example:
>>> d = NoCaseDict() >>> d['Content-Type'] = 'text/html' >>> print(d['Content-Type']) text/html >>> print(d['content-type']) text/html >>> print(d['CONTENT-TYPE']) text/html >>> del d['cOnTeNt-TyPe'] >>> print(d) {}
- get(key, default=None)¶
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F. ¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- class microdot.MultiDict(initial_dict=None)¶
A subclass of dictionary that can hold multiple values for the same key. It is used to hold key/value pairs decoded from query strings and form submissions.
- Parameters:
initial_dict – an initial dictionary of key/value pairs to initialize this object with.
Example:
>>> d = MultiDict() >>> d['sort'] = 'name' >>> d['sort'] = 'email' >>> print(d['sort']) 'name' >>> print(d.getlist('sort')) ['name', 'email']
- get(key, default=None, type=None)¶
Return the value for a given key.
- Parameters:
key – The key to retrieve.
default – A default value to use if the key does not exist.
type – A type conversion callable to apply to the value.
If the multidict contains more than one value for the requested key, this method returns the first value only.
Example:
>>> d = MultiDict() >>> d['age'] = '42' >>> d.get('age') '42' >>> d.get('age', type=int) 42 >>> d.get('name', default='noname') 'noname'
- getlist(key, type=None)¶
Return all the values for a given key.
- Parameters:
key – The key to retrieve.
type – A type conversion callable to apply to the values.
If the requested key does not exist in the dictionary, this method returns an empty list.
Example:
>>> d = MultiDict() >>> d.getlist('items') [] >>> d['items'] = '3' >>> d.getlist('items') ['3'] >>> d['items'] = '56' >>> d.getlist('items') ['3', '56'] >>> d.getlist('items', type=int) [3, 56]
microdot_asyncio
module¶
- class microdot_asyncio.Microdot¶
- 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.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 isFalse
.ssl – An
SSLContext
instance orNone
if the server should not use TLS. The default isNone
.
This method is a coroutine.
Example:
import asyncio from microdot_asyncio 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.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 isFalse
.ssl – An
SSLContext
instance orNone
if the server should not use TLS. The default isNone
.
Example:
from microdot_asyncio 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...'
- 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()
- 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
- 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
- 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): # ...
- 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 withmethods=['DELETE']
.Example:
@app.delete('/users/<int:id>') def delete_user(request, id): # ...
- 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'
- 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 withmethods=['GET']
.Example:
@app.get('/users/<int:id>') def get_user(request, id): # ...
- 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.
- 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 withmethods=['PATCH']
.Example:
@app.patch('/users/<int:id>') def edit_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 withmethods=['PUT']
.Example:
@app.put('/users/<int:id>') def edit_user(request, id): # ...
- 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 bestring
(the default),int
,path
orre:[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!'
- class microdot_asyncio.Request(app, client_addr, method, url, http_version, headers, body=None, stream=None, sock=None)¶
- 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 stream¶
The input stream, containing the request body.
- 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.
- property body¶
The body of the request, as bytes.
- property form¶
The parsed form submission body, as a
MultiDict
object, orNone
if the request does not have a form submission.
- property json¶
The parsed JSON body, or
None
if the request does not have a JSON body.
- 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_length
bytes 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_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_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
- socket_read_timeout = 1¶
Specify a suggested read timeout to use when reading the request. Set to 0 to disable the use of a timeout. This timeout should be considered a suggestion only, as some platforms may not support it. The default is 1 second.
- 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.
- path¶
The path portion of the URL.
- query_string¶
The query string portion of the URL.
- headers¶
A dictionary with the headers included in the request.
- cookies¶
A dictionary with the cookies included in the request.
- content_length¶
The parsed
Content-Length
header.
- content_type¶
The parsed
Content-Type
header.
- g¶
A general purpose container for applications to store data during the life of the request.
- class microdot_asyncio.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.
- already_handled = <microdot_asyncio.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.
- 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 ofNone
means that noCache-Control
header is added.
- 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 thefilename
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 theContent-Type
header.max_age – The
Cache-Control
header’smax-age
value in seconds. If omitted, the value of theResponse.default_send_file_max_age
attribute is used.compressed – Whether the file is compressed. If
True
, theContent-Encoding
header 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
filename
parameter when opening the file, including the dot. The extension given here is not considered when generating theContent-Type
header.
Security note: The filename is assumed to be trusted. Never pass filenames provided by the user without validating and sanitizing them first.
- set_cookie(cookie, value, path=None, domain=None, expires=None, max_age=None, secure=False, http_only=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
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.
microdot_utemplate
module¶
- microdot_utemplate.init_templates(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 therecompile.Loader
class, which automatically recompiles templates when they change.
- microdot_utemplate.render_template(template, *args, **kwargs)¶
Render a template.
- Parameters:
template – The filename of the template to render, relative to the configured template directory.
args – Positional arguments to be passed to the render engine.
kwargs – Keyword arguments to be passed to the render engine.
The return value is an iterator that returns sections of rendered template.
microdot_jinja
module¶
- microdot_jinja.init_templates(template_dir='templates')¶
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.
- microdot_jinja.render_template(template, *args, **kwargs)¶
Render a template.
- Parameters:
template – The filename of the template to render, relative to the configured template directory.
args – Positional arguments to be passed to the render engine.
kwargs – Keyword arguments to be passed to the render engine.
The return value is a string with the rendered template.
microdot_session
module¶
microdot_cors
module¶
- 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 totrue
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.
microdot_websocket
module¶
- 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') def echo(request): if not authenticate_user(request): abort(401) ws = websocket_upgrade(request) while True: message = ws.receive() 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 def echo(request, ws): while True: message = ws.receive() ws.send(message)
microdot_asyncio_websocket
module¶
- async microdot_asyncio_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_asyncio_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)
microdot_asgi_websocket
module¶
- async microdot_asgi_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 (await authenticate_user(request)): abort(401) ws = await websocket_upgrade(request) while True: message = await ws.receive() await ws.send(message)
- microdot_asgi_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)
microdot_ssl
module¶
- microdot_ssl.create_ssl_context(cert, key, **kwargs)¶
Create an SSL context to wrap sockets with.
- Parameters:
cert – The certificate to use. If it is given as a string, it is assumed to be a filename. If it is given as a bytes object, it is assumed to be the certificate data. In both cases the data is expected to be in PEM format for CPython and in DER format for MicroPython.
key – The private key to use. If it is given as a string, it is assumed to be a filename. If it is given as a bytes object, it is assumed to be the private key data. in both cases the data is expected to be in PEM format for CPython and in DER format for MicroPython.
kwargs – Additional arguments to pass to the
ssl.wrap_socket
function.
Note: This function creates a fairly limited SSL context object to enable the use of certificates under MicroPython. It is not intended to be used in any other context, and in particular, it is not needed when using CPython or any other Python implementation that has native support for
SSLContext
objects. Once MicroPython implementsSSLContext
natively, this function will be deprecated.
microdot_test_client
module¶
- 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('/') def index(): return 'Hello, World!' def test_hello_world(self): client = TestClient(app) res = client.get('/') assert res.status_code == 200 assert res.text == 'Hello, World!'
- 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.
- 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.
- 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.
- 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.
- 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.
- 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 toNone
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.
microdot_asyncio_test_client
module¶
- class microdot_asyncio_test_client.TestClient(app, cookies=None)¶
A test client for Microdot’s Asynchronous web server.
- 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_asyncio 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_asyncio_test_client.TestResponse¶
A response object issued by the Microdot test client.