Module hug.route

hug/route.py

Defines user usable routers

Copyright (C) 2016 Timothy Edmund Crosley

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View Source
"""hug/route.py

Defines user usable routers

Copyright (C) 2016  Timothy Edmund Crosley

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated

documentation files (the "Software"), to deal in the Software without restriction, including without limitation

the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and

to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or

substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED

TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

OTHER DEALINGS IN THE SOFTWARE.

"""

from __future__ import absolute_import

from functools import partial

from types import FunctionType, MethodType

from falcon import HTTP_METHODS

import hug.api

from hug.routing import CLIRouter as cli  # noqa:  N813

from hug.routing import ExceptionRouter as exception  # noqa:  N813

from hug.routing import LocalRouter as local  # noqa:  N813

from hug.routing import NotFoundRouter as not_found  # noqa:  N813

from hug.routing import SinkRouter as sink  # noqa:  N813

from hug.routing import StaticRouter as static  # noqa:  N813

from hug.routing import URLRouter as http  # noqa:  N813

class Object(http):

    """Defines a router for classes and objects"""

    def __init__(self, urls=None, accept=HTTP_METHODS, output=None, **kwargs):

        super().__init__(urls=urls, accept=accept, output=output, **kwargs)

    def __call__(self, method_or_class=None, **kwargs):

        if not method_or_class and kwargs:

            return self.where(**kwargs)

        if isinstance(method_or_class, (MethodType, FunctionType)):

            routes = getattr(method_or_class, "_hug_http_routes", [])

            routes.append(self.route)

            method_or_class._hug_http_routes = routes

            return method_or_class

        instance = method_or_class

        if isinstance(method_or_class, type):

            instance = method_or_class()

        for argument in dir(instance):

            argument = getattr(instance, argument, None)

            http_routes = getattr(argument, "_hug_http_routes", ())

            for route in http_routes:

                http(**self.where(**route).route)(argument)

            cli_routes = getattr(argument, "_hug_cli_routes", ())

            for route in cli_routes:

                cli(**self.where(**route).route)(argument)

        return method_or_class

    def http_methods(self, urls=None, **route_data):

        """Creates routes from a class, where the class method names should line up to HTTP METHOD types"""

        def decorator(class_definition):

            instance = class_definition

            if isinstance(class_definition, type):

                instance = class_definition()

            router = self.urls(

                urls if urls else "/{0}".format(instance.__class__.__name__.lower()), **route_data

            )

            for method in HTTP_METHODS:

                handler = getattr(instance, method.lower(), None)

                if handler:

                    http_routes = getattr(handler, "_hug_http_routes", ())

                    if http_routes:

                        for route in http_routes:

                            http(**router.accept(method).where(**route).route)(handler)

                    else:

                        http(**router.accept(method).route)(handler)

                    cli_routes = getattr(handler, "_hug_cli_routes", ())

                    if cli_routes:

                        for route in cli_routes:

                            cli(**self.where(**route).route)(handler)

            return class_definition

        return decorator

    def cli(self, method):

        """Registers a method on an Object as a CLI route"""

        routes = getattr(method, "_hug_cli_routes", [])

        routes.append(self.route)

        method._hug_cli_routes = routes

        return method

class API(object):

    """Provides a convient way to route functions to a single API independent of where they live"""

    __slots__ = ("api",)

    def __init__(self, api):

        if type(api) == str:

            api = hug.api.API(api)

        self.api = api

    def http(self, *args, **kwargs):

        """Starts the process of building a new HTTP route linked to this API instance"""

        kwargs["api"] = self.api

        return http(*args, **kwargs)

    def urls(self, *args, **kwargs):

        """DEPRECATED: for backwords compatibility with < hug 2.2.0. `API.http` should be used instead.

           Starts the process of building a new URL HTTP route linked to this API instance

        """

        return self.http(*args, **kwargs)

    def not_found(self, *args, **kwargs):

        """Defines the handler that should handle not found requests against this API"""

        kwargs["api"] = self.api

        return not_found(*args, **kwargs)

    def static(self, *args, **kwargs):

        """Define the routes to static files the API should expose"""

        kwargs["api"] = self.api

        return static(*args, **kwargs)

    def sink(self, *args, **kwargs):

        """Define URL prefixes/handler matches where everything under the URL prefix should be handled"""

        kwargs["api"] = self.api

        return sink(*args, **kwargs)

    def exception(self, *args, **kwargs):

        """Defines how this API should handle the provided exceptions"""

        kwargs["api"] = self.api

        return exception(*args, **kwargs)

    def cli(self, *args, **kwargs):

        """Defines a CLI function that should be routed by this API"""

        kwargs["api"] = self.api

        return cli(*args, **kwargs)

    def object(self, *args, **kwargs):

        """Registers a class based router to this API"""

        kwargs["api"] = self.api

        return Object(*args, **kwargs)

    def get(self, *args, **kwargs):

        """Builds a new GET HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("GET",)

        return http(*args, **kwargs)

    def post(self, *args, **kwargs):

        """Builds a new POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("POST",)

        return http(*args, **kwargs)

    def put(self, *args, **kwargs):

        """Builds a new PUT HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PUT",)

        return http(*args, **kwargs)

    def delete(self, *args, **kwargs):

        """Builds a new DELETE HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("DELETE",)

        return http(*args, **kwargs)

    def connect(self, *args, **kwargs):

        """Builds a new CONNECT HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("CONNECT",)

        return http(*args, **kwargs)

    def head(self, *args, **kwargs):

        """Builds a new HEAD HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("HEAD",)

        return http(*args, **kwargs)

    def options(self, *args, **kwargs):

        """Builds a new OPTIONS HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("OPTIONS",)

        return http(*args, **kwargs)

    def patch(self, *args, **kwargs):

        """Builds a new PATCH HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PATCH",)

        return http(*args, **kwargs)

    def trace(self, *args, **kwargs):

        """Builds a new TRACE HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("TRACE",)

        return http(*args, **kwargs)

    def get_post(self, *args, **kwargs):

        """Builds a new GET or POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("GET", "POST")

        return http(*args, **kwargs)

    def put_post(self, *args, **kwargs):

        """Builds a new PUT or POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PUT", "POST")

        return http(*args, **kwargs)

for method in HTTP_METHODS:

    method_handler = partial(http, accept=(method,))

    method_handler.__doc__ = "Exposes a Python method externally as an HTTP {0} method".format(

        method.upper()

    )

    globals()[method.lower()] = method_handler

get_post = partial(http, accept=("GET", "POST"))

get_post.__doc__ = "Exposes a Python method externally under both the HTTP POST and GET methods"

put_post = partial(http, accept=("PUT", "POST"))

put_post.__doc__ = "Exposes a Python method externally under both the HTTP POST and PUT methods"

object = Object()

# DEPRECATED: for backwords compatibility with hug 1.x.x

call = http

Variables

HTTP_METHODS
connect
delete
get
get_post
head
method
method_handler
object
options
patch
post
put
put_post
trace

Classes

API

class API(
    api
)

Provides a convient way to route functions to a single API independent of where they live

View Source
class API(object):

    """Provides a convient way to route functions to a single API independent of where they live"""

    __slots__ = ("api",)

    def __init__(self, api):

        if type(api) == str:

            api = hug.api.API(api)

        self.api = api

    def http(self, *args, **kwargs):

        """Starts the process of building a new HTTP route linked to this API instance"""

        kwargs["api"] = self.api

        return http(*args, **kwargs)

    def urls(self, *args, **kwargs):

        """DEPRECATED: for backwords compatibility with < hug 2.2.0. `API.http` should be used instead.

           Starts the process of building a new URL HTTP route linked to this API instance

        """

        return self.http(*args, **kwargs)

    def not_found(self, *args, **kwargs):

        """Defines the handler that should handle not found requests against this API"""

        kwargs["api"] = self.api

        return not_found(*args, **kwargs)

    def static(self, *args, **kwargs):

        """Define the routes to static files the API should expose"""

        kwargs["api"] = self.api

        return static(*args, **kwargs)

    def sink(self, *args, **kwargs):

        """Define URL prefixes/handler matches where everything under the URL prefix should be handled"""

        kwargs["api"] = self.api

        return sink(*args, **kwargs)

    def exception(self, *args, **kwargs):

        """Defines how this API should handle the provided exceptions"""

        kwargs["api"] = self.api

        return exception(*args, **kwargs)

    def cli(self, *args, **kwargs):

        """Defines a CLI function that should be routed by this API"""

        kwargs["api"] = self.api

        return cli(*args, **kwargs)

    def object(self, *args, **kwargs):

        """Registers a class based router to this API"""

        kwargs["api"] = self.api

        return Object(*args, **kwargs)

    def get(self, *args, **kwargs):

        """Builds a new GET HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("GET",)

        return http(*args, **kwargs)

    def post(self, *args, **kwargs):

        """Builds a new POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("POST",)

        return http(*args, **kwargs)

    def put(self, *args, **kwargs):

        """Builds a new PUT HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PUT",)

        return http(*args, **kwargs)

    def delete(self, *args, **kwargs):

        """Builds a new DELETE HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("DELETE",)

        return http(*args, **kwargs)

    def connect(self, *args, **kwargs):

        """Builds a new CONNECT HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("CONNECT",)

        return http(*args, **kwargs)

    def head(self, *args, **kwargs):

        """Builds a new HEAD HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("HEAD",)

        return http(*args, **kwargs)

    def options(self, *args, **kwargs):

        """Builds a new OPTIONS HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("OPTIONS",)

        return http(*args, **kwargs)

    def patch(self, *args, **kwargs):

        """Builds a new PATCH HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PATCH",)

        return http(*args, **kwargs)

    def trace(self, *args, **kwargs):

        """Builds a new TRACE HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("TRACE",)

        return http(*args, **kwargs)

    def get_post(self, *args, **kwargs):

        """Builds a new GET or POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("GET", "POST")

        return http(*args, **kwargs)

    def put_post(self, *args, **kwargs):

        """Builds a new PUT or POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PUT", "POST")

        return http(*args, **kwargs)

Instance variables

api

Methods

cli
def cli(
    self,
    *args,
    **kwargs
)

Defines a CLI function that should be routed by this API

View Source
    def cli(self, *args, **kwargs):

        """Defines a CLI function that should be routed by this API"""

        kwargs["api"] = self.api

        return cli(*args, **kwargs)
connect
def connect(
    self,
    *args,
    **kwargs
)

Builds a new CONNECT HTTP route that is registered to this API

View Source
    def connect(self, *args, **kwargs):

        """Builds a new CONNECT HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("CONNECT",)

        return http(*args, **kwargs)
delete
def delete(
    self,
    *args,
    **kwargs
)

Builds a new DELETE HTTP route that is registered to this API

View Source
    def delete(self, *args, **kwargs):

        """Builds a new DELETE HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("DELETE",)

        return http(*args, **kwargs)
exception
def exception(
    self,
    *args,
    **kwargs
)

Defines how this API should handle the provided exceptions

View Source
    def exception(self, *args, **kwargs):

        """Defines how this API should handle the provided exceptions"""

        kwargs["api"] = self.api

        return exception(*args, **kwargs)
get
def get(
    self,
    *args,
    **kwargs
)

Builds a new GET HTTP route that is registered to this API

View Source
    def get(self, *args, **kwargs):

        """Builds a new GET HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("GET",)

        return http(*args, **kwargs)
get_post
def get_post(
    self,
    *args,
    **kwargs
)

Builds a new GET or POST HTTP route that is registered to this API

View Source
    def get_post(self, *args, **kwargs):

        """Builds a new GET or POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("GET", "POST")

        return http(*args, **kwargs)
def head(
    self,
    *args,
    **kwargs
)

Builds a new HEAD HTTP route that is registered to this API

View Source
    def head(self, *args, **kwargs):

        """Builds a new HEAD HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("HEAD",)

        return http(*args, **kwargs)
http
def http(
    self,
    *args,
    **kwargs
)

Starts the process of building a new HTTP route linked to this API instance

View Source
    def http(self, *args, **kwargs):

        """Starts the process of building a new HTTP route linked to this API instance"""

        kwargs["api"] = self.api

        return http(*args, **kwargs)
not_found
def not_found(
    self,
    *args,
    **kwargs
)

Defines the handler that should handle not found requests against this API

View Source
    def not_found(self, *args, **kwargs):

        """Defines the handler that should handle not found requests against this API"""

        kwargs["api"] = self.api

        return not_found(*args, **kwargs)
object
def object(
    self,
    *args,
    **kwargs
)

Registers a class based router to this API

View Source
    def object(self, *args, **kwargs):

        """Registers a class based router to this API"""

        kwargs["api"] = self.api

        return Object(*args, **kwargs)
options
def options(
    self,
    *args,
    **kwargs
)

Builds a new OPTIONS HTTP route that is registered to this API

View Source
    def options(self, *args, **kwargs):

        """Builds a new OPTIONS HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("OPTIONS",)

        return http(*args, **kwargs)
patch
def patch(
    self,
    *args,
    **kwargs
)

Builds a new PATCH HTTP route that is registered to this API

View Source
    def patch(self, *args, **kwargs):

        """Builds a new PATCH HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PATCH",)

        return http(*args, **kwargs)
post
def post(
    self,
    *args,
    **kwargs
)

Builds a new POST HTTP route that is registered to this API

View Source
    def post(self, *args, **kwargs):

        """Builds a new POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("POST",)

        return http(*args, **kwargs)
put
def put(
    self,
    *args,
    **kwargs
)

Builds a new PUT HTTP route that is registered to this API

View Source
    def put(self, *args, **kwargs):

        """Builds a new PUT HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PUT",)

        return http(*args, **kwargs)
put_post
def put_post(
    self,
    *args,
    **kwargs
)

Builds a new PUT or POST HTTP route that is registered to this API

View Source
    def put_post(self, *args, **kwargs):

        """Builds a new PUT or POST HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("PUT", "POST")

        return http(*args, **kwargs)
sink
def sink(
    self,
    *args,
    **kwargs
)

Define URL prefixes/handler matches where everything under the URL prefix should be handled

View Source
    def sink(self, *args, **kwargs):

        """Define URL prefixes/handler matches where everything under the URL prefix should be handled"""

        kwargs["api"] = self.api

        return sink(*args, **kwargs)
static
def static(
    self,
    *args,
    **kwargs
)

Define the routes to static files the API should expose

View Source
    def static(self, *args, **kwargs):

        """Define the routes to static files the API should expose"""

        kwargs["api"] = self.api

        return static(*args, **kwargs)
trace
def trace(
    self,
    *args,
    **kwargs
)

Builds a new TRACE HTTP route that is registered to this API

View Source
    def trace(self, *args, **kwargs):

        """Builds a new TRACE HTTP route that is registered to this API"""

        kwargs["api"] = self.api

        kwargs["accept"] = ("TRACE",)

        return http(*args, **kwargs)
urls
def urls(
    self,
    *args,
    **kwargs
)

DEPRECATED: for backwords compatibility with < hug 2.2.0. API.http should be used instead.

Starts the process of building a new URL HTTP route linked to this API instance

View Source
    def urls(self, *args, **kwargs):

        """DEPRECATED: for backwords compatibility with < hug 2.2.0. `API.http` should be used instead.

           Starts the process of building a new URL HTTP route linked to this API instance

        """

        return self.http(*args, **kwargs)

Object

class Object(
    urls=None,
    accept=('CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE'),
    output=None,
    **kwargs
)

Defines a router for classes and objects

View Source
class Object(http):

    """Defines a router for classes and objects"""

    def __init__(self, urls=None, accept=HTTP_METHODS, output=None, **kwargs):

        super().__init__(urls=urls, accept=accept, output=output, **kwargs)

    def __call__(self, method_or_class=None, **kwargs):

        if not method_or_class and kwargs:

            return self.where(**kwargs)

        if isinstance(method_or_class, (MethodType, FunctionType)):

            routes = getattr(method_or_class, "_hug_http_routes", [])

            routes.append(self.route)

            method_or_class._hug_http_routes = routes

            return method_or_class

        instance = method_or_class

        if isinstance(method_or_class, type):

            instance = method_or_class()

        for argument in dir(instance):

            argument = getattr(instance, argument, None)

            http_routes = getattr(argument, "_hug_http_routes", ())

            for route in http_routes:

                http(**self.where(**route).route)(argument)

            cli_routes = getattr(argument, "_hug_cli_routes", ())

            for route in cli_routes:

                cli(**self.where(**route).route)(argument)

        return method_or_class

    def http_methods(self, urls=None, **route_data):

        """Creates routes from a class, where the class method names should line up to HTTP METHOD types"""

        def decorator(class_definition):

            instance = class_definition

            if isinstance(class_definition, type):

                instance = class_definition()

            router = self.urls(

                urls if urls else "/{0}".format(instance.__class__.__name__.lower()), **route_data

            )

            for method in HTTP_METHODS:

                handler = getattr(instance, method.lower(), None)

                if handler:

                    http_routes = getattr(handler, "_hug_http_routes", ())

                    if http_routes:

                        for route in http_routes:

                            http(**router.accept(method).where(**route).route)(handler)

                    else:

                        http(**router.accept(method).route)(handler)

                    cli_routes = getattr(handler, "_hug_cli_routes", ())

                    if cli_routes:

                        for route in cli_routes:

                            cli(**self.where(**route).route)(handler)

            return class_definition

        return decorator

    def cli(self, method):

        """Registers a method on an Object as a CLI route"""

        routes = getattr(method, "_hug_cli_routes", [])

        routes.append(self.route)

        method._hug_cli_routes = routes

        return method

Ancestors (in MRO)

  • hug.route.URLRouter
  • hug.routing.HTTPRouter
  • hug.routing.InternalValidation
  • hug.routing.Router

Class variables

route

Methods

accept
def accept(
    self,
    *accept,
    **overrides
)

Sets a list of HTTP methods this router should accept

View Source
    def accept(self, *accept, **overrides):

        """Sets a list of HTTP methods this router should accept"""

        return self.where(accept=accept, **overrides)
add_response_headers
def add_response_headers(
    self,
    headers,
    **overrides
)

Adds the specified response headers while keeping existing ones in-tact

View Source
    def add_response_headers(self, headers, **overrides):

        """Adds the specified response headers while keeping existing ones in-tact"""

        response_headers = self.route.get("response_headers", {}).copy()

        response_headers.update(headers)

        return self.where(response_headers=response_headers, **overrides)
allow_origins
def allow_origins(
    self,
    *origins,
    methods=None,
    max_age=None,
    credentials=None,
    headers=None,
    **overrides
)

Convenience method for quickly allowing other resources to access this one

View Source
    def allow_origins(

        self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides

    ):

        """Convenience method for quickly allowing other resources to access this one"""

        response_headers = {}

        if origins:

            @hug.response_middleware(api=self.route.get("api", None))

            def process_data(request, response, resource):

                if "ORIGIN" in request.headers:

                    origin = request.headers["ORIGIN"]

                    if origin in origins:

                        response.set_header("Access-Control-Allow-Origin", origin)

        else:

            response_headers["Access-Control-Allow-Origin"] = "*"

        if methods:

            response_headers["Access-Control-Allow-Methods"] = ", ".join(methods)

        if max_age:

            response_headers["Access-Control-Max-Age"] = max_age

        if credentials:

            response_headers["Access-Control-Allow-Credentials"] = str(credentials).lower()

        if headers:

            response_headers["Access-Control-Allow-Headers"] = headers

        return self.add_response_headers(response_headers, **overrides)
api
def api(
    self,
    api,
    **overrides
)

Sets the API that should contain this route

View Source
    def api(self, api, **overrides):

        """Sets the API that should contain this route"""

        return self.where(api=api, **overrides)
cache
def cache(
    self,
    private=False,
    max_age=31536000,
    s_maxage=None,
    no_cache=False,
    no_store=False,
    must_revalidate=False,
    **overrides
)

Convenience method for quickly adding cache header to route

View Source
    def cache(

        self,

        private=False,

        max_age=31536000,

        s_maxage=None,

        no_cache=False,

        no_store=False,

        must_revalidate=False,

        **overrides

    ):

        """Convenience method for quickly adding cache header to route"""

        parts = (

            "private" if private else "public",

            "max-age={0}".format(max_age),

            "s-maxage={0}".format(s_maxage) if s_maxage is not None else None,

            no_cache and "no-cache",

            no_store and "no-store",

            must_revalidate and "must-revalidate",

        )

        return self.add_response_headers(

            {"cache-control": ", ".join(filter(bool, parts))}, **overrides

        )
call
def call(
    self,
    **overrides
)

Sets the acceptable HTTP method to all known

View Source
    def call(self, **overrides):

        """Sets the acceptable HTTP method to all known"""

        return self.where(accept=HTTP_METHODS, **overrides)
cli
def cli(
    self,
    method
)

Registers a method on an Object as a CLI route

View Source
    def cli(self, method):

        """Registers a method on an Object as a CLI route"""

        routes = getattr(method, "_hug_cli_routes", [])

        routes.append(self.route)

        method._hug_cli_routes = routes

        return method
connect
def connect(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to CONNECT

View Source
    def connect(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to CONNECT"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="CONNECT", **overrides)
defaults
def defaults(
    self,
    defaults,
    **overrides
)

Sets the custom defaults that will be used for custom parameters

View Source
    def defaults(self, defaults, **overrides):

        """Sets the custom defaults that will be used for custom parameters"""

        return self.where(defaults=defaults, **overrides)
delete
def delete(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to DELETE

View Source
    def delete(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to DELETE"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="DELETE", **overrides)
doesnt_require
def doesnt_require(
    self,
    requirements,
    **overrides
)

Removes individual requirements while keeping all other defined ones within a route

View Source
    def doesnt_require(self, requirements, **overrides):

        """Removes individual requirements while keeping all other defined ones within a route"""

        return self.where(

            requires=tuple(

                set(self.route.get("requires", ())).difference(

                    requirements if type(requirements) in (list, tuple) else (requirements,)

                )

            )

        )
examples
def examples(
    self,
    *examples,
    **overrides
)

Sets the examples that the route should use

View Source
    def examples(self, *examples, **overrides):

        """Sets the examples that the route should use"""

        return self.where(examples=examples, **overrides)
get
def get(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to a GET

View Source
    def get(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to a GET"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="GET", **overrides)
get_post
def get_post(
    self,
    **overrides
)

Exposes a Python method externally under both the HTTP POST and GET methods

View Source
    def get_post(self, **overrides):

        """Exposes a Python method externally under both the HTTP POST and GET methods"""

        return self.where(accept=("GET", "POST"), **overrides)
head
def head(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to HEAD

View Source
    def head(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to HEAD"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="HEAD", **overrides)
http
def http(
    self,
    **overrides
)

Sets the acceptable HTTP method to all known

View Source
    def http(self, **overrides):

        """Sets the acceptable HTTP method to all known"""

        return self.where(accept=HTTP_METHODS, **overrides)
http_methods
def http_methods(
    self,
    urls=None,
    **route_data
)

Creates routes from a class, where the class method names should line up to HTTP METHOD types

View Source
    def http_methods(self, urls=None, **route_data):

        """Creates routes from a class, where the class method names should line up to HTTP METHOD types"""

        def decorator(class_definition):

            instance = class_definition

            if isinstance(class_definition, type):

                instance = class_definition()

            router = self.urls(

                urls if urls else "/{0}".format(instance.__class__.__name__.lower()), **route_data

            )

            for method in HTTP_METHODS:

                handler = getattr(instance, method.lower(), None)

                if handler:

                    http_routes = getattr(handler, "_hug_http_routes", ())

                    if http_routes:

                        for route in http_routes:

                            http(**router.accept(method).where(**route).route)(handler)

                    else:

                        http(**router.accept(method).route)(handler)

                    cli_routes = getattr(handler, "_hug_cli_routes", ())

                    if cli_routes:

                        for route in cli_routes:

                            cli(**self.where(**route).route)(handler)

            return class_definition

        return decorator
map_params
def map_params(
    self,
    **map_params
)

Map interface specific params to an internal name representation

View Source
    def map_params(self, **map_params):

        """Map interface specific params to an internal name representation"""

        return self.where(map_params=map_params)
on_invalid
def on_invalid(
    self,
    function,
    **overrides
)

Sets a function to use to transform data on validation errors.

Defaults to the transform function if one is set to ensure no special handling occurs for invalid data set to False.

View Source
    def on_invalid(self, function, **overrides):

        """Sets a function to use to transform data on validation errors.

        Defaults to the transform function if one is set to ensure no special

        handling occurs for invalid data set to `False`.

        """

        return self.where(on_invalid=function, **overrides)
options
def options(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to OPTIONS

View Source
    def options(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to OPTIONS"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="OPTIONS", **overrides)
output
def output(
    self,
    formatter,
    **overrides
)

Sets the output formatter that should be used to render this route

View Source
    def output(self, formatter, **overrides):

        """Sets the output formatter that should be used to render this route"""

        return self.where(output=formatter, **overrides)
output_invalid
def output_invalid(
    self,
    output_handler,
    **overrides
)

Sets an output handler to be used when handler validation fails.

Defaults to the output formatter set globally for the route.

View Source
    def output_invalid(self, output_handler, **overrides):

        """Sets an output handler to be used when handler validation fails.

        Defaults to the output formatter set globally for the route.

        """

        return self.where(output_invalid=output_handler, **overrides)
parameters
def parameters(
    self,
    parameters,
    **overrides
)

Sets the custom parameters that will be used instead of those found introspecting the decorated function

View Source
    def parameters(self, parameters, **overrides):

        """Sets the custom parameters that will be used instead of those found introspecting the decorated function"""

        return self.where(parameters=parameters, **overrides)
parse_body
def parse_body(
    self,
    automatic=True,
    **overrides
)

Tells hug to automatically parse the input body if it matches a registered input format

View Source
    def parse_body(self, automatic=True, **overrides):

        """Tells hug to automatically parse the input body if it matches a registered input format"""

        return self.where(parse_body=automatic, **overrides)
patch
def patch(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to PATCH

View Source
    def patch(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to PATCH"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="PATCH", **overrides)
post
def post(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to POST

View Source
    def post(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to POST"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="POST", **overrides)
prefixes
def prefixes(
    self,
    *prefixes,
    **overrides
)

Sets the prefixes supported by the route

View Source
    def prefixes(self, *prefixes, **overrides):

        """Sets the prefixes supported by the route"""

        return self.where(prefixes=prefixes, **overrides)
put
def put(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to PUT

View Source
    def put(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to PUT"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="PUT", **overrides)
put_post
def put_post(
    self,
    **overrides
)

Exposes a Python method externally under both the HTTP POST and PUT methods

View Source
    def put_post(self, **overrides):

        """Exposes a Python method externally under both the HTTP POST and PUT methods"""

        return self.where(accept=("PUT", "POST"), **overrides)
raise_on_invalid
def raise_on_invalid(
    self,
    setting=True,
    **overrides
)

Sets the route to raise validation errors instead of catching them

View Source
    def raise_on_invalid(self, setting=True, **overrides):

        """Sets the route to raise validation errors instead of catching them"""

        return self.where(raise_on_invalid=setting, **overrides)
requires
def requires(
    self,
    requirements,
    **overrides
)

Adds additional requirements to the specified route

View Source
    def requires(self, requirements, **overrides):

        """Adds additional requirements to the specified route"""

        return self.where(

            requires=tuple(self.route.get("requires", ())) + tuple(requirements), **overrides

        )
response_headers
def response_headers(
    self,
    headers,
    **overrides
)

Sets the response headers automatically injected by the router

View Source
    def response_headers(self, headers, **overrides):

        """Sets the response headers automatically injected by the router"""

        return self.where(response_headers=headers, **overrides)
set_status
def set_status(
    self,
    status,
    **overrides
)

Sets the status that will be returned by default

View Source
    def set_status(self, status, **overrides):

        """Sets the status that will be returned by default"""

        return self.where(status=status, **overrides)
suffixes
def suffixes(
    self,
    *suffixes,
    **overrides
)

Sets the suffixes supported by the route

View Source
    def suffixes(self, *suffixes, **overrides):

        """Sets the suffixes supported by the route"""

        return self.where(suffixes=suffixes, **overrides)
trace
def trace(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to TRACE

View Source
    def trace(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to TRACE"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="TRACE", **overrides)
transform
def transform(
    self,
    function,
    **overrides
)

Sets the function that should be used to transform the returned Python structure into something serializable by specified output format

View Source
    def transform(self, function, **overrides):

        """Sets the function that should be used to transform the returned Python structure into something

           serializable by specified output format

        """

        return self.where(transform=function, **overrides)
urls
def urls(
    self,
    *urls,
    **overrides
)

Sets the URLs that will map to this API call

View Source
    def urls(self, *urls, **overrides):

        """Sets the URLs that will map to this API call"""

        return self.where(urls=urls, **overrides)
validate
def validate(
    self,
    validation_function,
    **overrides
)

Sets the secondary validation fucntion to use for this handler

View Source
    def validate(self, validation_function, **overrides):

        """Sets the secondary validation fucntion to use for this handler"""

        return self.where(validate=validation_function, **overrides)
versions
def versions(
    self,
    supported,
    **overrides
)

Sets the versions that this route should be compatiable with

View Source
    def versions(self, supported, **overrides):

        """Sets the versions that this route should be compatiable with"""

        return self.where(versions=supported, **overrides)
where
def where(
    self,
    **overrides
)

Creates a new route, based on the current route, with the specified overrided values

View Source
    def where(self, **overrides):

        if "urls" in overrides:

            existing_urls = self.route.get("urls", ())

            use_urls = []

            for url in (

                (overrides["urls"],) if isinstance(overrides["urls"], str) else overrides["urls"]

            ):

                if url.startswith("/") or not existing_urls:

                    use_urls.append(url)

                else:

                    for existing in existing_urls:

                        use_urls.append(urljoin(existing.rstrip("/") + "/", url))

            overrides["urls"] = tuple(use_urls)

        return super().where(**overrides)

call

class call(
    urls=None,
    accept=('CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE'),
    output=None,
    examples=(),
    versions=<built-in function any>,
    suffixes=(),
    prefixes=(),
    response_headers=None,
    parse_body=True,
    **kwargs
)

Provides a chainable router that can be used to route a URL to a Python function

View Source
class URLRouter(HTTPRouter):

    """Provides a chainable router that can be used to route a URL to a Python function"""

    __slots__ = ()

    def __init__(

        self,

        urls=None,

        accept=HTTP_METHODS,

        output=None,

        examples=(),

        versions=any,

        suffixes=(),

        prefixes=(),

        response_headers=None,

        parse_body=True,

        **kwargs

    ):

        super().__init__(

            output=output,

            versions=versions,

            parse_body=parse_body,

            response_headers=response_headers,

            **kwargs

        )

        if urls is not None:

            self.route["urls"] = (urls,) if isinstance(urls, str) else urls

        if accept:

            self.route["accept"] = (accept,) if isinstance(accept, str) else accept

        if examples:

            self.route["examples"] = (examples,) if isinstance(examples, str) else examples

        if suffixes:

            self.route["suffixes"] = (suffixes,) if isinstance(suffixes, str) else suffixes

        if prefixes:

            self.route["prefixes"] = (prefixes,) if isinstance(prefixes, str) else prefixes

    def __call__(self, api_function):

        api = self.route.get("api", hug.api.from_object(api_function))

        api.http.routes.setdefault(api.http.base_url, OrderedDict())

        (interface, callable_method) = self._create_interface(api, api_function)

        use_examples = self.route.get("examples", ())

        if not interface.required and not use_examples:

            use_examples = (True,)

        for base_url in self.route.get("urls", ("/{0}".format(api_function.__name__),)):

            expose = [base_url]

            for suffix in self.route.get("suffixes", ()):

                if suffix.startswith("/"):

                    expose.append(os.path.join(base_url, suffix.lstrip("/")))

                else:

                    expose.append(base_url + suffix)

            for prefix in self.route.get("prefixes", ()):

                expose.append(prefix + base_url)

            for url in expose:

                handlers = api.http.routes[api.http.base_url].setdefault(url, {})

                for method in self.route.get("accept", ()):

                    version_mapping = handlers.setdefault(method.upper(), {})

                    for version in self.route.get("versions", (None,)):

                        version_mapping[version] = interface

                        api.http.versioned.setdefault(version, {})[

                            callable_method.__name__

                        ] = callable_method

        interface.examples = use_examples

        return callable_method

    def urls(self, *urls, **overrides):

        """Sets the URLs that will map to this API call"""

        return self.where(urls=urls, **overrides)

    def accept(self, *accept, **overrides):

        """Sets a list of HTTP methods this router should accept"""

        return self.where(accept=accept, **overrides)

    def get(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to a GET"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="GET", **overrides)

    def delete(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to DELETE"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="DELETE", **overrides)

    def post(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to POST"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="POST", **overrides)

    def put(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to PUT"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="PUT", **overrides)

    def trace(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to TRACE"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="TRACE", **overrides)

    def patch(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to PATCH"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="PATCH", **overrides)

    def options(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to OPTIONS"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="OPTIONS", **overrides)

    def head(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to HEAD"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="HEAD", **overrides)

    def connect(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to CONNECT"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="CONNECT", **overrides)

    def call(self, **overrides):

        """Sets the acceptable HTTP method to all known"""

        return self.where(accept=HTTP_METHODS, **overrides)

    def http(self, **overrides):

        """Sets the acceptable HTTP method to all known"""

        return self.where(accept=HTTP_METHODS, **overrides)

    def get_post(self, **overrides):

        """Exposes a Python method externally under both the HTTP POST and GET methods"""

        return self.where(accept=("GET", "POST"), **overrides)

    def put_post(self, **overrides):

        """Exposes a Python method externally under both the HTTP POST and PUT methods"""

        return self.where(accept=("PUT", "POST"), **overrides)

    def examples(self, *examples, **overrides):

        """Sets the examples that the route should use"""

        return self.where(examples=examples, **overrides)

    def suffixes(self, *suffixes, **overrides):

        """Sets the suffixes supported by the route"""

        return self.where(suffixes=suffixes, **overrides)

    def prefixes(self, *prefixes, **overrides):

        """Sets the prefixes supported by the route"""

        return self.where(prefixes=prefixes, **overrides)

    def where(self, **overrides):

        if "urls" in overrides:

            existing_urls = self.route.get("urls", ())

            use_urls = []

            for url in (

                (overrides["urls"],) if isinstance(overrides["urls"], str) else overrides["urls"]

            ):

                if url.startswith("/") or not existing_urls:

                    use_urls.append(url)

                else:

                    for existing in existing_urls:

                        use_urls.append(urljoin(existing.rstrip("/") + "/", url))

            overrides["urls"] = tuple(use_urls)

        return super().where(**overrides)

Ancestors (in MRO)

  • hug.routing.HTTPRouter
  • hug.routing.InternalValidation
  • hug.routing.Router

Descendants

  • hug.route.Object

Class variables

route

Methods

accept
def accept(
    self,
    *accept,
    **overrides
)

Sets a list of HTTP methods this router should accept

View Source
    def accept(self, *accept, **overrides):

        """Sets a list of HTTP methods this router should accept"""

        return self.where(accept=accept, **overrides)
add_response_headers
def add_response_headers(
    self,
    headers,
    **overrides
)

Adds the specified response headers while keeping existing ones in-tact

View Source
    def add_response_headers(self, headers, **overrides):

        """Adds the specified response headers while keeping existing ones in-tact"""

        response_headers = self.route.get("response_headers", {}).copy()

        response_headers.update(headers)

        return self.where(response_headers=response_headers, **overrides)
allow_origins
def allow_origins(
    self,
    *origins,
    methods=None,
    max_age=None,
    credentials=None,
    headers=None,
    **overrides
)

Convenience method for quickly allowing other resources to access this one

View Source
    def allow_origins(

        self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides

    ):

        """Convenience method for quickly allowing other resources to access this one"""

        response_headers = {}

        if origins:

            @hug.response_middleware(api=self.route.get("api", None))

            def process_data(request, response, resource):

                if "ORIGIN" in request.headers:

                    origin = request.headers["ORIGIN"]

                    if origin in origins:

                        response.set_header("Access-Control-Allow-Origin", origin)

        else:

            response_headers["Access-Control-Allow-Origin"] = "*"

        if methods:

            response_headers["Access-Control-Allow-Methods"] = ", ".join(methods)

        if max_age:

            response_headers["Access-Control-Max-Age"] = max_age

        if credentials:

            response_headers["Access-Control-Allow-Credentials"] = str(credentials).lower()

        if headers:

            response_headers["Access-Control-Allow-Headers"] = headers

        return self.add_response_headers(response_headers, **overrides)
api
def api(
    self,
    api,
    **overrides
)

Sets the API that should contain this route

View Source
    def api(self, api, **overrides):

        """Sets the API that should contain this route"""

        return self.where(api=api, **overrides)
cache
def cache(
    self,
    private=False,
    max_age=31536000,
    s_maxage=None,
    no_cache=False,
    no_store=False,
    must_revalidate=False,
    **overrides
)

Convenience method for quickly adding cache header to route

View Source
    def cache(

        self,

        private=False,

        max_age=31536000,

        s_maxage=None,

        no_cache=False,

        no_store=False,

        must_revalidate=False,

        **overrides

    ):

        """Convenience method for quickly adding cache header to route"""

        parts = (

            "private" if private else "public",

            "max-age={0}".format(max_age),

            "s-maxage={0}".format(s_maxage) if s_maxage is not None else None,

            no_cache and "no-cache",

            no_store and "no-store",

            must_revalidate and "must-revalidate",

        )

        return self.add_response_headers(

            {"cache-control": ", ".join(filter(bool, parts))}, **overrides

        )
call
def call(
    self,
    **overrides
)

Sets the acceptable HTTP method to all known

View Source
    def call(self, **overrides):

        """Sets the acceptable HTTP method to all known"""

        return self.where(accept=HTTP_METHODS, **overrides)
connect
def connect(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to CONNECT

View Source
    def connect(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to CONNECT"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="CONNECT", **overrides)
defaults
def defaults(
    self,
    defaults,
    **overrides
)

Sets the custom defaults that will be used for custom parameters

View Source
    def defaults(self, defaults, **overrides):

        """Sets the custom defaults that will be used for custom parameters"""

        return self.where(defaults=defaults, **overrides)
delete
def delete(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to DELETE

View Source
    def delete(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to DELETE"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="DELETE", **overrides)
doesnt_require
def doesnt_require(
    self,
    requirements,
    **overrides
)

Removes individual requirements while keeping all other defined ones within a route

View Source
    def doesnt_require(self, requirements, **overrides):

        """Removes individual requirements while keeping all other defined ones within a route"""

        return self.where(

            requires=tuple(

                set(self.route.get("requires", ())).difference(

                    requirements if type(requirements) in (list, tuple) else (requirements,)

                )

            )

        )
examples
def examples(
    self,
    *examples,
    **overrides
)

Sets the examples that the route should use

View Source
    def examples(self, *examples, **overrides):

        """Sets the examples that the route should use"""

        return self.where(examples=examples, **overrides)
get
def get(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to a GET

View Source
    def get(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to a GET"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="GET", **overrides)
get_post
def get_post(
    self,
    **overrides
)

Exposes a Python method externally under both the HTTP POST and GET methods

View Source
    def get_post(self, **overrides):

        """Exposes a Python method externally under both the HTTP POST and GET methods"""

        return self.where(accept=("GET", "POST"), **overrides)
head
def head(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to HEAD

View Source
    def head(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to HEAD"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="HEAD", **overrides)
http
def http(
    self,
    **overrides
)

Sets the acceptable HTTP method to all known

View Source
    def http(self, **overrides):

        """Sets the acceptable HTTP method to all known"""

        return self.where(accept=HTTP_METHODS, **overrides)
map_params
def map_params(
    self,
    **map_params
)

Map interface specific params to an internal name representation

View Source
    def map_params(self, **map_params):

        """Map interface specific params to an internal name representation"""

        return self.where(map_params=map_params)
on_invalid
def on_invalid(
    self,
    function,
    **overrides
)

Sets a function to use to transform data on validation errors.

Defaults to the transform function if one is set to ensure no special handling occurs for invalid data set to False.

View Source
    def on_invalid(self, function, **overrides):

        """Sets a function to use to transform data on validation errors.

        Defaults to the transform function if one is set to ensure no special

        handling occurs for invalid data set to `False`.

        """

        return self.where(on_invalid=function, **overrides)
options
def options(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to OPTIONS

View Source
    def options(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to OPTIONS"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="OPTIONS", **overrides)
output
def output(
    self,
    formatter,
    **overrides
)

Sets the output formatter that should be used to render this route

View Source
    def output(self, formatter, **overrides):

        """Sets the output formatter that should be used to render this route"""

        return self.where(output=formatter, **overrides)
output_invalid
def output_invalid(
    self,
    output_handler,
    **overrides
)

Sets an output handler to be used when handler validation fails.

Defaults to the output formatter set globally for the route.

View Source
    def output_invalid(self, output_handler, **overrides):

        """Sets an output handler to be used when handler validation fails.

        Defaults to the output formatter set globally for the route.

        """

        return self.where(output_invalid=output_handler, **overrides)
parameters
def parameters(
    self,
    parameters,
    **overrides
)

Sets the custom parameters that will be used instead of those found introspecting the decorated function

View Source
    def parameters(self, parameters, **overrides):

        """Sets the custom parameters that will be used instead of those found introspecting the decorated function"""

        return self.where(parameters=parameters, **overrides)
parse_body
def parse_body(
    self,
    automatic=True,
    **overrides
)

Tells hug to automatically parse the input body if it matches a registered input format

View Source
    def parse_body(self, automatic=True, **overrides):

        """Tells hug to automatically parse the input body if it matches a registered input format"""

        return self.where(parse_body=automatic, **overrides)
patch
def patch(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to PATCH

View Source
    def patch(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to PATCH"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="PATCH", **overrides)
post
def post(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to POST

View Source
    def post(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to POST"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="POST", **overrides)
prefixes
def prefixes(
    self,
    *prefixes,
    **overrides
)

Sets the prefixes supported by the route

View Source
    def prefixes(self, *prefixes, **overrides):

        """Sets the prefixes supported by the route"""

        return self.where(prefixes=prefixes, **overrides)
put
def put(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to PUT

View Source
    def put(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to PUT"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="PUT", **overrides)
put_post
def put_post(
    self,
    **overrides
)

Exposes a Python method externally under both the HTTP POST and PUT methods

View Source
    def put_post(self, **overrides):

        """Exposes a Python method externally under both the HTTP POST and PUT methods"""

        return self.where(accept=("PUT", "POST"), **overrides)
raise_on_invalid
def raise_on_invalid(
    self,
    setting=True,
    **overrides
)

Sets the route to raise validation errors instead of catching them

View Source
    def raise_on_invalid(self, setting=True, **overrides):

        """Sets the route to raise validation errors instead of catching them"""

        return self.where(raise_on_invalid=setting, **overrides)
requires
def requires(
    self,
    requirements,
    **overrides
)

Adds additional requirements to the specified route

View Source
    def requires(self, requirements, **overrides):

        """Adds additional requirements to the specified route"""

        return self.where(

            requires=tuple(self.route.get("requires", ())) + tuple(requirements), **overrides

        )
response_headers
def response_headers(
    self,
    headers,
    **overrides
)

Sets the response headers automatically injected by the router

View Source
    def response_headers(self, headers, **overrides):

        """Sets the response headers automatically injected by the router"""

        return self.where(response_headers=headers, **overrides)
set_status
def set_status(
    self,
    status,
    **overrides
)

Sets the status that will be returned by default

View Source
    def set_status(self, status, **overrides):

        """Sets the status that will be returned by default"""

        return self.where(status=status, **overrides)
suffixes
def suffixes(
    self,
    *suffixes,
    **overrides
)

Sets the suffixes supported by the route

View Source
    def suffixes(self, *suffixes, **overrides):

        """Sets the suffixes supported by the route"""

        return self.where(suffixes=suffixes, **overrides)
trace
def trace(
    self,
    urls=None,
    **overrides
)

Sets the acceptable HTTP method to TRACE

View Source
    def trace(self, urls=None, **overrides):

        """Sets the acceptable HTTP method to TRACE"""

        if urls is not None:

            overrides["urls"] = urls

        return self.where(accept="TRACE", **overrides)
transform
def transform(
    self,
    function,
    **overrides
)

Sets the function that should be used to transform the returned Python structure into something serializable by specified output format

View Source
    def transform(self, function, **overrides):

        """Sets the function that should be used to transform the returned Python structure into something

           serializable by specified output format

        """

        return self.where(transform=function, **overrides)
urls
def urls(
    self,
    *urls,
    **overrides
)

Sets the URLs that will map to this API call

View Source
    def urls(self, *urls, **overrides):

        """Sets the URLs that will map to this API call"""

        return self.where(urls=urls, **overrides)
validate
def validate(
    self,
    validation_function,
    **overrides
)

Sets the secondary validation fucntion to use for this handler

View Source
    def validate(self, validation_function, **overrides):

        """Sets the secondary validation fucntion to use for this handler"""

        return self.where(validate=validation_function, **overrides)
versions
def versions(
    self,
    supported,
    **overrides
)

Sets the versions that this route should be compatiable with

View Source
    def versions(self, supported, **overrides):

        """Sets the versions that this route should be compatiable with"""

        return self.where(versions=supported, **overrides)
where
def where(
    self,
    **overrides
)

Creates a new route, based on the current route, with the specified overrided values

View Source
    def where(self, **overrides):

        if "urls" in overrides:

            existing_urls = self.route.get("urls", ())

            use_urls = []

            for url in (

                (overrides["urls"],) if isinstance(overrides["urls"], str) else overrides["urls"]

            ):

                if url.startswith("/") or not existing_urls:

                    use_urls.append(url)

                else:

                    for existing in existing_urls:

                        use_urls.append(urljoin(existing.rstrip("/") + "/", url))

            overrides["urls"] = tuple(use_urls)

        return super().where(**overrides)