API

application Module

Application

class nanohttp.application.Application(root=None)[source]

Bases: object

Application main handler

__logger__ = <Logger nanohttp (INFO)>

Application logger based on python builtin logging module

__root__ = None

The root controller

__init__(root=None)[source]

Initialize application and calling app_init hook.

Note

__root__ attribute will set by root parameter.

Parameters:root – The root controller

configuration Module

configure

nanohttp.configuration.configure(*args, **kwargs)[source]

Load configurations

Parameters:
  • args – positional arguments pass into pymlconf.DeferredRoot.load
  • kwargs – keyword arguments pass into pymlconf.DeferredRoot.load

contexts Module

Context

class nanohttp.contexts.Context(environ, application=None)[source]

Bases: object

A Global context for Request and Response.

Context are initialized and entering on every request (referring to
nanohttp application lifecycle).

Context also supports to use stack nested (>=0.16.6), its useful on testing.

def sample:
    return context.query['weather']

with Context({'QUERY_STRING': 'weather=Sunny'}):
    assert sample() == 'Sunny

    with Context({'QUERY_STRING': 'weather=Rainy'}):
        assert sample() == 'Rainy'
application = None

Current Application instance

cookies() → http.cookies.SimpleCookie[source]

Cookies

encode_response(buffer)[source]

Encode response buffer with encoding definition on current context

form()[source]

Request form values

Note

if using multipart/form-data uploaded file will reproduce as cgi.FieldStorage.

classmethod get_current() → nanohttp.contexts.Context[source]

Get current context

Not initialized context raises ContextIsNotInitializedError,

method()[source]

HTTP Request method

path()[source]

Request path

query()[source]

Request query string

request_content_length() → Optional[int][source]

Request content length

request_content_type() → Optional[str][source]

Request content type

request_scheme()[source]

Request Scheme (http|https)

request_uri()[source]

Request full URI (includes query string)

response_content_type

Response content type property

response_encoding = None

Response encoding

thread_local = <_thread._local object>

Thread local variable contexts stored in

controllers Module

Controller

class nanohttp.controllers.Controller[source]

Bases: object

Base Controller

RestController

class nanohttp.controllers.RestController[source]

Bases: nanohttp.controllers.Controller

HTTP method oriented controller

Static

class nanohttp.controllers.Static(directory='.', default_document='index.html')[source]

Bases: nanohttp.controllers.Controller

Serves static files

RegexRouteController

class nanohttp.controllers.RegexRouteController(routes)[source]

Bases: nanohttp.controllers.Controller

This is how to use it:

class Root(RegexRouteController):

    def __init__(self):
        super().__init__((
            ('/installations/(?P<installation_id>\d+)/access_tokens',
            self.access_tokens),
        ))

    @json
    def access_tokens(self, installation_id: int):
        return dict(
            installationId=installation_id
        )

decorators Module

nanohttp.decorators.action(*args, verbs: Union[str, list, tuple] = 'any', encoding: str = 'utf-8', content_type: Optional[str] = None, inner_decorator: Optional[callable] = None, prevent_empty_form=None, prevent_form=None, form_whitelist=None, **kwargs)[source]

Base action decorator

Marks the function as a nanohttp handler/action.

Parameters:
  • verbs – Allowed HTTP methods
  • encoding – Content encoding
  • content_type – Response Content Type
  • inner_decorator – Inner decorator, to put it between this decorator and the handler.
  • prevent_empty_form – Boolean or str, indicates to prevent empty HTTP form. if str given, a HTTPStatus(<str>) will be raised. otherwise HTTPBadRequest.
  • prevent_form – Boolean or str, indicates to prevent any HTTP form. if str given, a HTTPStatus(<str>) will be raised, otherwise HTTPBadRequest.
  • form_whitelist – A list of allowed form fields. or a tuple(list, httpstatus)
nanohttp.decorators.binary(*args, verbs: Union[str, list, tuple] = 'any', encoding: str = None, content_type: Optional[str] = 'application/octet-stream', inner_decorator: Optional[callable] = None, prevent_empty_form=None, prevent_form=None, form_whitelist=None, **kwargs)

Binary-data action decorator

nanohttp.decorators.chunked(trailer_field=None, trailer_value=None)[source]

Enables chunked encoding on an action

nanohttp.decorators.html(*args, verbs: Union[str, list, tuple] = 'any', encoding: str = 'utf-8', content_type: Optional[str] = 'text/html', inner_decorator: Optional[callable] = None, prevent_empty_form=None, prevent_form=None, form_whitelist=None, **kwargs)

HTML action decorator

nanohttp.decorators.json(*args, verbs: Union[str, list, tuple] = 'any', encoding: str = 'utf-8', content_type: Optional[str] = 'application/json', inner_decorator: Optional[callable] = <function jsonify>, prevent_empty_form=None, prevent_form=None, form_whitelist=None, **kwargs)

JSON action decorator

accepts list, dict, int, str or objects have to_dict method.

nanohttp.decorators.text(*args, verbs: Union[str, list, tuple] = 'any', encoding: str = 'utf-8', content_type: Optional[str] = 'text/plain', inner_decorator: Optional[callable] = None, prevent_empty_form=None, prevent_form=None, form_whitelist=None, **kwargs)

Plain Text action decorator

nanohttp.decorators.xml(*args, verbs: Union[str, list, tuple] = 'any', encoding: str = 'utf-8', content_type: Optional[str] = 'application/xml', inner_decorator: Optional[callable] = None, prevent_empty_form=None, prevent_form=None, form_whitelist=None, **kwargs)

XML action decorator

validations Module

nanohttp.validation.validate(**fields)[source]

Decorator to validate HTTP Forms and query string.

@validate(field1=dict(required=True))
def index(self, *, field1):
    ...

Available parameters for validation is listed below:

Parameters:
  • required – Boolean or str, indicates the field is required.
  • not_none – Boolean or str, Raise when field is given and it’s value is None.
  • type – A callable to pass the received value to it as the only argument and get it in the apprpriate type, Both ValueError and TypeError` may be raised if the value cannot casted to the specified type. A good example of this callable would be the int.
  • minimum – Numeric, Minimum allowed value.
  • maximum – Numeric, Maximum allowed value.
  • pattern – Regex pattern to match the value.
  • min_length – Only for strings, the minumum allowed length of the value.
  • max_length – Only for strings, the maximum allowed length of the value.
  • callback – A callable(value, container, field: Field) to be called while validating the field.

A detailed example:

my_validator = validate(
    title=dict(
        required='710 Title not in form',
        max_length=(50, '704 At most 50 characters are valid for title')
    ),
    description=dict(
        max_length=(
            512,
            '703 At most 512 characters are valid for description'
        )
    ),
    dueDate=dict(
        pattern=(DATE_PATTERN, '701 Invalid due date format'),
        required='711 Due date not in form'
    ),
    cutoff=dict(
        pattern=(DATE_PATTERN, '702 Invalid cutoff format'),
        required='712 Cutoff not in form'
    ),
)

@json
@my_validator
def index(self):
    ...

Field

class nanohttp.validation.Field(title, form=True, query=False, required=None, type_=None, minimum=None, maximum=None, pattern=None, min_length=None, max_length=None, callback=None, not_none=None, readonly=None)[source]

Bases: object

class nanohttp.validation.Criterion(expression)[source]

Bases: object

class nanohttp.validation.RequiredValidator(expression)[source]

Bases: nanohttp.validation.FlagCriterion

class nanohttp.validation.NotNoneValidator(expression)[source]

Bases: nanohttp.validation.FlagCriterion

class nanohttp.validation.TypeValidator(expression)[source]

Bases: nanohttp.validation.Criterion

class nanohttp.validation.MinLengthValidator(expression)[source]

Bases: nanohttp.validation.Criterion

class nanohttp.validation.MaxLengthValidator(expression)[source]

Bases: nanohttp.validation.Criterion

class nanohttp.validation.MinimumValidator(expression)[source]

Bases: nanohttp.validation.Criterion

class nanohttp.validation.MaximumValidator(expression)[source]

Bases: nanohttp.validation.Criterion

class nanohttp.validation.PatternValidator(expression)[source]

Bases: nanohttp.validation.Criterion

class nanohttp.validation.CallableValidator(expression)[source]

Bases: nanohttp.validation.Criterion

class nanohttp.validation.RequestValidator(fields, empty_form=None)[source]

Bases: object

exceptions Module

exception nanohttp.exceptions.HTTPAccepted(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPSuccess

exception nanohttp.exceptions.HTTPBadGatewayError(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPBadRequest(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPConflict(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPCreated(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPSuccess

exception nanohttp.exceptions.HTTPForbidden(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPFound(location, *args, **kw)[source]

Bases: nanohttp.exceptions.HTTPRedirect

exception nanohttp.exceptions.HTTPGone(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPInternalServerError(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPKnownStatus(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPStatus

exception nanohttp.exceptions.HTTPMethodNotAllowed(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPMovedPermanently(location, *args, **kw)[source]

Bases: nanohttp.exceptions.HTTPRedirect

exception nanohttp.exceptions.HTTPNoContent(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPSuccess

exception nanohttp.exceptions.HTTPNonAuthoritativeInformation(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPSuccess

exception nanohttp.exceptions.HTTPNotFound(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPNotModified(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPPartialContent(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPSuccess

exception nanohttp.exceptions.HTTPPreconditionFailed(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPRedirect(location, *args, **kw)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

This is an abstract class for all redirects.

exception nanohttp.exceptions.HTTPResetContent(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPSuccess

exception nanohttp.exceptions.HTTPStatus(status=None)[source]

Bases: Exception

exception nanohttp.exceptions.HTTPSuccess(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus

exception nanohttp.exceptions.HTTPUnauthorized(status_text=None)[source]

Bases: nanohttp.exceptions.HTTPKnownStatus