class documentation

Klein is an object which is responsible for maintaining the routing configuration of our application.

Method __eq__ Undocumented
Method __get__ Get an instance of Klein bound to instance.
Method __init__ Undocumented
Method __ne__ Undocumented
Method execute_endpoint Execute the named endpoint with all arguments and possibly a bound instance.
Method execute_error_handler Execute the passed error handler, possibly with a bound instance.
Method handle_errors Register an error handler. This decorator supports two syntaxes. The simpler of these can be used to register a handler for all Exception types:
Method resource Return an IResource which suitably wraps this app.
Method route Add a new handler for url passing args and kwargs directly to werkzeug.routing.Rule. The handler function will be passed at least one argument an twisted.web.server.Request and any keyword arguments taken from the ...
Method run Run a minimal twisted.web server on the specified port, bound to the interface specified by host and logging to logFile.
Method subroute Within this block, @route adds rules to a werkzeug.routing.Submount.
Method urlFor Undocumented
Property endpoints Read only property exposing Klein._endpoints.
Property url_map Read only property exposing Klein._url_map.
Static Method _segments_in_url Undocumented
Class Variable _subroute_segments Undocumented
Instance Variable _boundAs Undocumented
Instance Variable _endpoints A dict mapping endpoint names to handler functions.
Instance Variable _error_handlers Undocumented
Instance Variable _instance Undocumented
Instance Variable _url_map A werkzeug.routing.Map object which will be used for routing resolution.
def __eq__(self, other): (source)

Undocumented

Parameters
other:AnyUndocumented
Returns
boolUndocumented
def __get__(self, instance, owner): (source)

Get an instance of Klein bound to instance.

Parameters
instance:AnyUndocumented
owner:objectUndocumented
Returns
KleinUndocumented
def __init__(self): (source)

Undocumented

def __ne__(self, other): (source)

Undocumented

Parameters
other:AnyUndocumented
Returns
boolUndocumented
def execute_endpoint(self, endpoint, request, *args, **kwargs): (source)

Execute the named endpoint with all arguments and possibly a bound instance.

Parameters
endpoint:strUndocumented
request:IRequestUndocumented
*args:AnyUndocumented
**kwargs:AnyUndocumented
Returns
KleinRenderableUndocumented
def execute_error_handler(self, handler, request, failure): (source)

Execute the passed error handler, possibly with a bound instance.

Parameters
handler:KleinErrorMethodUndocumented
request:IRequestUndocumented
failure:FailureUndocumented
Returns
KleinRenderableUndocumented
def handle_errors(self, f_or_exception, *additional_exceptions): (source)

Register an error handler. This decorator supports two syntaxes. The simpler of these can be used to register a handler for all Exception types:

    @app.handle_errors
    def error_handler(request, failure):
        request.setResponseCode(500)
        return 'Uh oh'

Alternately, a handler can be registered for one or more specific Exception types:

    @app.handle_errors(EncodingError, ValidationError):
    def error_handler(request, failure)
        request.setResponseCode(400)
        return failure.getTraceback()

The handler will be passed a twisted.web.server.Request as well as a twisted.python.failure.Failure instance. Error handlers may return a deferred, a failure or a response body.

If more than one error handler is registered, the handlers will be executed in the order in which they are defined, until a handler is encountered which completes successfully. If no handler completes successfully, twisted.web.server.Request's processingFailed() method will be called.

In addition to handling errors that occur within a KleinRouteHandler, error handlers also handle any werkzeug.exceptions.HTTPException which is raised during request routing.

In particular, werkzeug.exceptions.NotFound will be raised if no matching route is found, so to return a custom 404 users can do the following:

    @app.handle_errors(NotFound)
    def error_handler(request, failure):
        request.setResponseCode(404)
        return 'Not found'
Parameters
f_or_exception:Union[KleinErrorHandler, Type[Exception]]An error handler function, or an Exception subclass to scope the decorated handler to.
*additional_exceptions:Type[Exception]Additional Exception subclasses to scope the decorated function to.
Returns
Callable[[KleinErrorHandler], Callable]decorated error handler function.
def resource(self): (source)

Return an IResource which suitably wraps this app.

Returns
KleinResourceAn IResource
def route(self, url, *args, **kwargs): (source)

Add a new handler for url passing args and kwargs directly to werkzeug.routing.Rule. The handler function will be passed at least one argument an twisted.web.server.Request and any keyword arguments taken from the url pattern.

:

    @app.route("/")
    def index(request):
        return "Hello"
Parameters
url:strA werkzeug URL pattern given to werkzeug.routing.Rule.
*args:AnyUndocumented
**kwargs:AnyUndocumented
branchA bool indiciated if a branch endpoint should be added that allows all child path segments that don't match some other route to be consumed. Default False.
Returns
Callable[[KleinRouteHandler], KleinRouteHandler]decorated handler function.
def run(self, host=None, port=None, logFile=None, endpoint_description=None, displayTracebacks=True): (source)

Run a minimal twisted.web server on the specified port, bound to the interface specified by host and logging to logFile.

This function will run the default reactor for your platform and so will block the main thread of your application. It should be the last thing your klein application does.

Parameters
host:Optional[str]The hostname or IP address to bind the listening socket to. "0.0.0.0" will allow you to listen on all interfaces, and "127.0.0.1" will allow you to listen on just the loopback interface.
port:Optional[int]The TCP port to accept HTTP requests on.
logFile:Optional[IO]The file object to log to, by default sys.stdout
endpoint_description:Optional[str]specification of endpoint. Must contain protocol, port and interface. May contain other optional arguments, e.g. to use SSL: "ssl:443:privateKey=key.pem:certKey=crt.pem"
displayTracebacks:boolWeather a processing error will result in a page displaying the traceback with debugging information or not.
@contextmanager
def subroute(self, prefix): (source)

Within this block, @route adds rules to a werkzeug.routing.Submount.

This is implemented by tinkering with the instance's _url_map variable. A context manager allows us to gracefully use the pattern of "change a variable, do some things with the new value, then put it back to how it was before.

Named "subroute" to try and give callers a better idea of its relationship to @route.

Usage: :

    with app.subroute("/prefix") as app:
        @app.route("/foo")
        def foo_handler(request):
            return 'I respond to /prefix/foo'
Parameters
prefix:strThe string that will be prepended to the paths of all routes established during the with-block.
Returns
Iterator[Klein]Undocumented
def urlFor(self, request, endpoint, values=None, method=None, force_external=False, append_unknown=True): (source)

Undocumented

Parameters
request:IRequestUndocumented
endpoint:strUndocumented
values:Optional[Mapping[str, KleinQueryValue]]Undocumented
method:Optional[str]Undocumented
force_external:boolUndocumented
append_unknown:boolUndocumented
Returns
strUndocumented
@property
endpoints: Dict[str, KleinRouteHandler] = (source)

Read only property exposing Klein._endpoints.

@property
url_map: Map = (source)

Read only property exposing Klein._url_map.

@staticmethod
def _segments_in_url(url): (source)

Undocumented

Parameters
url:strUndocumented
Returns
intUndocumented
_subroute_segments: int = (source)

Undocumented

_boundAs = (source)

Undocumented

_endpoints: Dict[str, KleinRouteHandler] = (source)

A dict mapping endpoint names to handler functions.

_error_handlers: ErrorHandlers = (source)

Undocumented

_instance: Optional[Klein] = (source)

Undocumented

_url_map = (source)

A werkzeug.routing.Map object which will be used for routing resolution.