API Documentation

itty3

The itty-bitty Python web framework… Now Rewritten For Python 3!

class itty3.App(debug=False)

Bases: object

An orchestration object that handles routing & request processing.

Parameters:debug (bool) – Allows for controlling a debugging mode.
add_route(method, path, func)

Adds a given HTTP method, URI path & view to the routing.

Parameters:
  • method (str) – The HTTP method to handle
  • path (str) – The URI path to handle
  • func (callable) – The view function to process a matching request
create_request(environ)

Given a WSGI environment, creates a HttpRequest object.

Parameters:environ (dict-alike) – The environment data coming from the WSGI server, including request information.
Returns:A built request object
Return type:HttpRequest
delete(path)

A convenience decorator for adding a view that processes a DELETE request to routing.

Example:

app = itty3.App()

@app.delete("/blog/<slug:post_slug>/")
def delete_post(request, post_slug):
    ...
Parameters:path (str) – The URI path to handle
error_404(request)

Generates a 404 page for when something isn’t found.

Exposed to allow for custom 404 pages. Care should be taken when overriding this function, as it is used internally by the routing & Python errors bubbling from within can break the server.

Parameters:request (HttpRequest) – The request being handled
Returns:The populated response object
Return type:HttpResponse
error_500(request)

Generates a 500 page for when something is broken.

Exposed to allow for custom 500 pages. Care should be taken when overriding this function, as it is used internally by the routing & Python errors bubbling from within can break the server.

Parameters:request (HttpRequest) – The request being handled
Returns:The populated response object
Return type:HttpResponse
find_route(method, path)

Determines the routing offset for a given HTTP method & URI path.

Parameters:
  • method (str) – The HTTP method to handle
  • path (str) – The URI path to handle
Returns:

The offset of the matching route

Return type:

int

Raises:

RouteNotFound – If a matching route is not found

get(path)

A convenience decorator for adding a view that processes a GET request to routing.

Example:

app = itty3.App()

@app.get("/blog/<slug:post_slug>/")
def post_detail(request, post_slug):
    ...
Parameters:path (str) – The URI path to handle
get_log()

Returns a logging.Logger instance.

By default, we return the itty3 module-level logger. Users are free to override this to meet their needs.

Returns:The module-level logger
Return type:logging.Logger
patch(path)

A convenience decorator for adding a view that processes a PATCH (partial update) request to routing.

Example:

app = itty3.App()

@app.patch("/blog/bulk/")
def bulk_post(request):
    ...
Parameters:path (str) – The URI path to handle
post(path)

A convenience decorator for adding a view that processes a POST request to routing.

Example:

app = itty3.App()

@app.post("/blog/create/")
def create_post(request):
    ...
Parameters:path (str) – The URI path to handle
process_request(environ, start_response)

Processes a specific WSGI request.

This kicks off routing & attempts to find a route matching the requested HTTP method & URI path.

If found, the view associated with the route is called, optionally with the parameters from the URI. The resulting HttpResponse then performs the actions to write the response to the server.

If not found, App.error_404 is called to produce a 404 page.

If an unhandled exception occurs, App.error_500 is called to produce a 500 page.

Parameters:
  • environ (dict-alike) – The environment data coming from the WSGI server, including request information.
  • start_response (callable) – The function/callable to execute when beginning a response.
Returns:

The body iterable for the WSGI server

Return type:

iterable

put(path)

A convenience decorator for adding a view that processes a PUT request to routing.

Example:

app = itty3.App()

@app.put("/blog/<slug:post_slug>/")
def update_post(request, post_slug):
    ...
Parameters:path (str) – The URI path to handle
redirect(request, url, permanent=False)

A convenience function for supplying a HTTP redirect.

Parameters:
  • request (HttpRequest) – The request being handled
  • url (str) – A path or full URL to redirect the user to
  • permanent (bool, Optional) – Whether the redirect should be considered permanent or not. Defaults to False (temporary redirect).
Returns:

The populated response object

Return type:

HttpResponse

remove_route(method, path)

Removes a route from the routing.

Parameters:
  • method (str) – The HTTP method to handle
  • path (str) – The URI path to handle
render(request, body, status_code=200, content_type='text/html', headers=None)

A convenience method for creating a HttpResponse object.

Parameters:
  • request (HttpRequest) – The request being handled
  • body (str) – The body of the response
  • status_code (int, Optional) – The HTTP status to return. Defaults to 200.
  • content_type (str, Optional) – The Content-Type header to return with the response. Defaults to text/html.
  • headers (dict, Optional) – The HTTP headers to include on the response. Defaults to empty headers.
Returns:

The populated response object

Return type:

HttpResponse

render_json(request, data, status_code=200, content_type='application/json', headers=None)

A convenience method for creating a JSON HttpResponse object.

Parameters:
  • request (HttpRequest) – The request being handled
  • data (dict/list) – The Python data structure to be encoded as JSON
  • status_code (int, Optional) – The HTTP status to return. Defaults to 200.
  • content_type (str, Optional) – The Content-Type header to return with the response. Defaults to text/html.
  • headers (dict, Optional) – The HTTP headers to include on the response. Defaults to empty headers.
Returns:

The populated response object

Return type:

HttpResponse

render_static(request, asset_path)

Handles serving static assets.

WARNING: This should really only be used in development!

It’s slow (compared to nginx, Apache or whatever), it hasn’t gone through any security assessments (which means potential security holes), it’s imperfect w/ regard to mimetypes.

Parameters:
  • request (HttpRequest) – The request being handled
  • asset_path (str) – A path of the asset to be served
Returns:

The populated response object

Return type:

HttpResponse

reset_logging(level=20)

A method for controlling how App.run does logging.

Disables wsgiref’s default “logging” to stderr & replaces it with itty3-specific logging.

Parameters:level (int, Optional) – The logging.LEVEL you’d like to have output. Default is logging.INFO.
Returns:
The handler class to be used.
Defaults to a custom NoStdErrHandler class.
Return type:wsgiref.WSGIRequestHandler
run(addr='127.0.0.1', port=8000, debug=None, static_url_path=None, static_root=None)

An included development/debugging server for running the App itself.

Runs indefinitely. Use Ctrl+C or a similar process killing method to exit the server.

Parameters:
  • addr (str, Optional) – The address to bind to. Defaults to 127.0.0.1.
  • port (int, Optional) – The port to bind to. Defaults to 8000.
  • debug (bool, Optional) – Whether the server should be run in a debugging mode. If provided, this overrides the App.debug set during initialization.
  • static_url_path (str, Optional) – The desired URL prefix for static assets. e.g. /static/. Defaults to None (no static serving).
  • static_root (str, Optional) – The filesystem path to the static assets. e.g. ../static_assets. Can be either a relative or absolute path. Defaults to None (no static serving).
class itty3.HttpRequest(uri, method, headers=None, body='', scheme='http', host='', port=80, content_length=0, request_protocol='HTTP/1.0', cookies=None)

Bases: object

A request object, representing all the portions of the HTTP request.

Parameters:
  • uri (str) – The URI being requested.
  • method (str) – The HTTP method (“GET|POST|PUT|DELETE|PATCH|HEAD”)
  • headers (dict, Optional) – The received HTTP headers
  • body (str, Optional) – The body of the HTTP request
  • scheme (str, Optional) – The HTTP scheme (“http|https”)
  • host (str, Optional) – The hostname of the request
  • port (int, Optional) – The port of the request
  • content_length (int, Optional) – The length of the body of the request
  • request_protocol (str, Optional) – The protocol of the request
  • cookies (http.cookies.SimpleCookie, Optional) – The cookies sent as part of the request.
GET

Returns a QueryDict of the GET parameters.

POST

Returns a QueryDict of the POST parameters from the request body.

Useless if the body isn’t form-encoded data, like JSON bodies.

PUT

Returns a QueryDict of the PUT parameters from the request body.

Useless if the body isn’t form-encoded data, like JSON bodies.

content_type()

Returns the received Content-Type header.

Returns:The content-type header or “text/html” if it was absent.
Return type:str
classmethod from_wsgi(environ)

Builds a new HttpRequest from the provided WSGI environ.

Parameters:environ (dict) – The bag of YOLO that is the WSGI environment
Returns:
A fleshed out request object, based on what was
present.
Return type:HttpRequest
get_status_line()
is_ajax()

Identifies if the request came from an AJAX call.

Returns:True if sent via AJAX, False otherwise
Return type:bool
is_secure()

Identifies whether or not the request was secure.

Returns:True if the environment specified HTTPs, False otherwise
Return type:bool
json()

Decodes a JSON body if present.

Returns:The data
Return type:dict
split_uri(full_uri)

Breaks a URI down into components.

Parameters:full_uri (str) – The URI to parse
Returns:
A dictionary of the components. Includes path, query
fragment, as well as netloc if host/port information is present.
Return type:dict
class itty3.HttpResponse(body='', status_code=200, headers=None, content_type='text/plain')

Bases: object

A response object, to make responding to requests easier.

A lightly-internal start_response attribute must be manually set on the response object when in a WSGI environment in order to send the response.

Parameters:
  • body (str, Optional) – The body of the response. Defaults to “”.
  • status_code (int, Optional) – The HTTP status code (without the reason). Default is 200.
  • headers (dict, Optional) – The headers to supply with the response. Default is empty headers.
  • content_type (str, Optional) – The content-type of the response. Default is text/plain.

Removes a cookie.

Succeed regards if the cookie is already set or not.

Parameters:
  • key (str) – The name of the cookie.
  • path (str, Optional) – The path the cookie is valid for. Default is “/”.
  • domain (str, Optional) – The domain the cookie is valid for. Default is None (only the domain that set it).

Sets a cookie on the response.

Takes the same parameters as the http.cookies.Morsel object from the Python stdlib.

Parameters:
  • key (str) – The name of the cookie.
  • value (Any) – The value of the cookie.
  • max_age (int, Optional) – How many seconds the cookie lives for. Default is None (expires at the end of the browser session).
  • expires (str or datetime, Optional) – A specific date/time (in UTC) when the cookie should expire. Default is None (expires at the end of the browser session).
  • path (str, Optional) – The path the cookie is valid for. Default is “/”.
  • domain (str, Optional) – The domain the cookie is valid for. Default is None (only the domain that set it).
  • secure (bool, Optional) – If the cookie should only be served by HTTPS. Default is False.
  • httponly (bool, Optional) – If True, prevents the cookie from being provided to Javascript requests. Default is False.
  • samesite (str, Optional) – How the cookie should behave under cross-site requests. Options are itty3.SAME_SITE_NONE, itty3.SAME_SITE_LAX, and itty3.SAME_SITE_STRICT. Default is None. Only for Python 3.8+.
set_header(name, value)

Sets a header on the response.

If the Content-Type header is provided, this also updates the value of HttpResponse.content_type.

Parameters:
  • name (str) – The name of the header.
  • value (Any) – The value of the header.
write()

Begins the transmission of the response.

The lightly-internal start_response attribute MUST be manually set on the object BEFORE calling this method! This callable is called during execution to set the status line & headers of the response.

Returns:An iterable of the content
Return type:iterable
Raises:ResponseFailed – If no start_response was set before calling.
exception itty3.IttyException

Bases: Exception

The base exception for all itty3 exceptions.

class itty3.QueryDict(data=None)

Bases: object

Simulates a dict-like object for query parameters.

Because HTTP allows for query strings to provide the same name for a parameter more than once, this object smoothes over the day-to-day usage of those queries.

You can act like it’s a plain dict if you only need a single value.

If you need all the values, QueryDict.getlist & QueryDict.setlist are available to expose the full list.

get(name, default=None)

Tries to fetch a value for a given name.

If not found, this returns the provided default.

Parameters:
  • name (str) – The name of the parameter you’d like to fetch
  • default (bool, defaults to None) – The value to return if the name isn’t found.
Returns:

The found value for the name, or the default.

Return type:

Any

getlist(name)

Tries to fetch all values for a given name.

Parameters:name (str) – The name of the parameter you’d like to fetch
Returns:The found values for the name.
Return type:list
Raises:KeyError – If the name isn’t found
items()

Returns all the parameter names & values.

Returns:
A list of two-tuples. The parameter names & the first
value for that name.
Return type:list
keys()

Returns all the parameter names.

Returns:A list of all the parameter names
Return type:list
setlist(name, values)

Sets all values for a given name.

Parameters:
  • name (str) – The name of the parameter you’d like to fetch
  • values (list) – The list of all values
Returns:

None

exception itty3.ResponseFailed

Bases: itty3.IttyException

Raised when a response could not be returned to the server/user.

class itty3.Route(method, path, func)

Bases: object

Handles setting up a given route. Composed of a HTTP method, a URI path & “view” (a callable function that takes a request & returns a response object) for handling a matching request.

Variables can be added to the path using a <type:variable_name> syntax. For instance, if you wanted to capture a UUID & an integer in a URI, you could provide the following path:

"/app/<uuid:app_id>/version/<int:major_version>/"

These would be added onto the call to the view as additional arguments. In the case of the previous path, the view’s signature should look like:

def app_info(request, app_id, major_version): ...

Supported types include:

  • str
  • int
  • float
  • slug
  • uuid
Parameters:
  • method (str) – The HTTP method
  • path (str) – The URI path to match against
  • func (callable) – The view function to handle a matching request
can_handle(method, path)

Determines if the route can handle a specific request.

Parameters:
  • method (str) – The HTTP method coming from the request
  • path (str) – The URI path coming from the request
Returns:

True if this route can handle the request, False otherwise

Return type:

bool

convert_types(matches)

Takes raw matched from requested URI path & converts the data to their proper type.

Parameters:matches (dict) – The variable names & the string data found for them from the URI path.
Returns:The converted data
Return type:dict
create_re(path)

Creates a compiled regular expression of a path.

It’d be unusual to need this as an end-user, but who am I to stop you? :)

Parameters:path (str) – A URI path, potentially with <type:variable_name> bits in it.
Returns:
A tuple of the compiled regular expression that suits the
path & dict of the variable names/type conversions to be done upon matching.
Return type:tuple
extract_kwargs(path)

Pulls variables out of the requested URI path.

Parameters:path (str) – The URI path coming from the request
Returns:
A dictionary of the variable names from the path &
converted data found for them. Empty dict if no variables were present.
Return type:dict
get_re_for_any()
get_re_for_float()
get_re_for_int()
get_re_for_slug()
get_re_for_type(desired_type)

Fetches the correct regex for a given type.

Parameters:desired_type (str) – The provided type to get a regex for
Returns:A raw string of the regex (minus the variable name)
Return type:str
get_re_for_uuid()
known_types = ['str', 'int', 'float', 'uuid', 'slug']
exception itty3.RouteNotFound

Bases: itty3.IttyException

Raised when no method/path combination could be found.

itty3.get_version(full=False)

Fetches the current version of itty3.

Parameters:full (bool) – Chooses between the short semver version and the longer/full version, including release information.
Returns:The version string
Return type:str