itty3 module¶
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
-
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
-
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
-
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
-
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
-
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
-
run
(addr='127.0.0.1', port=8000, debug=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.
-
class
itty3.
HttpRequest
(uri, method, headers=None, body='', scheme='http', host='', port=80)¶ 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
-
property
GET
¶ Returns a QueryDict of the GET parameters.
-
property
POST
¶ Returns a QueryDict of the POST parameters from the request body.
Useless if the body isn’t form-encoded data, like JSON bodies.
-
property
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
-
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.
-
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
-
known_types
= ['int', 'float', 'str', '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