API Reference

Left menu reflects interest’s pulic API. There are high-level abstraction elements on top and low-level abstraction elements on bottom grouped by responsibility.

Service

class interest.Service(service=None, *, name=None, prefix=None, methods=None, middlewares=None, endpoint=None, loop=None, router=None, logger=None, handler=None, providers=None)

Service is a middleware capable to listen on TCP/IP socket.

Service also provides methods Service.match(), Service.url() and Service.log() to use in request processing. This list can be updated via Provider system. Concrete service functionality is based on Router, Logger and Handler classes.

See also

Implements: Middleware, Chain, Config

Parameters

loop: object
Custom asyncio’s loop.
router: type
Router subclass.
logger: type
Logger subclass.
handler: type
Handler subclass.
providers: list
List of Provider subclasses.

Examples

Minimal service can be initiated without subclassing and parameters passed. But for example we will add some custom components:

# Create server
service = Service(
    router='<router>',
    logger='<logger>',
    handler='<handler>',
    providers=['<provider>'],
    middlewares=['<middleware>'])

# Listen forever
service.listen(host='127.0.0.1', port=9000, forever=True)
LOOP

Default loop parameter.

ROUTER

Default router parameter.

alias of Router

LOGGER

Default logger parameter.

alias of Logger

HANDLER

Default handler parameter.

alias of Handler

PROVIDERS = []

Default providers parameter.

loop

asyncio’s loop (read-only).

listen(*, host, port, override=False, forever=False, **kwargs)

Listen on TCP/IP socket.

Parameters

host: str
Host like ‘127.0.0.1’
port:
Port like 80.
match(request, *, root=None, path=None, methods=None)

Return match or None for the request/constraints pair.

See also

Proxy: Router.match()

url(name, *, base=None, query=None, **match)

Construct an url for the given parameters.

See also

Proxy: Router.url()

log(level, *args, **kwargs)

Log something.

See also

Proxy: Logger.level

Middleware

class interest.Middleware(service, *, name=None, prefix=None, methods=None, middlewares=None, endpoint=None)

Middleware is a extended coroutine to process requests.

Middleware is a key concept of the interest. For example Service and Endpoint are the Middlewares. The interest framework uses middlewares only as coroutines calling Middleware.__call__() method. But user application may use all provided API because of knowledge of the application topology.

See also

Implements: Chain, Config

Parameters

service: Service
Service instance.
name: str
Middleware’s name.
prefix: str
HTTP path prefix constraint.
methods: list
HTTP methods allowed constraint.
middlewares: list
List of submiddlewares.
endpoint: Endpoint subclass.
Default endpoint class for bindings.

Examples

Processing middleware:

class Middleware(Middleware):

    # Public

    @asyncio.coroutine
    def process(self, request):
        try:
            # Process request here
            response = yield from self.next(request)
            # Process response here
        except http.Exception as exception:
            # Process exception here
            response = exception
        return response

middleware = Middleware('<service>')
response = yield from middleware('<request>')
NAME

Default name parameter.

PREFIX = ''

Default prefix parameter.

METHODS = []

Default methods parameter.

MIDDLEWARES = []

Default middlewares parameter.

ENDPOINT = None

Default endpoint parameter.

__call__(request)

Process a request (coroutine).

Parameters

request: http.Request
Request instance.

Returns

object
Reply value.
service

Service instance (read-only).

name

Middleware’s name (read-only).

path

HTTP full path constraint. (read-only).

methods

HTTP methods allowed constraint (read-only).

process(request)

Process a request (coroutine).

Note

This coroutine will be reached only if request matches path and methods constraints.

By default this method sends request to submiddleware chain and returns reply. It’s standard point to override Middleware behavior by user application.

Parameters

request: http.Request
Request instance.

Returns

object
Reply value.
main(request)

Link to the main middleware (coroutine).

over(request)

Link to the over middleware (coroutine).

prev(request)

Link to the previous middleware (coroutine).

next(request)

Link to the next middleware (coroutine).

Endpoint

class interest.Endpoint(service, *, name=None, prefix=None, methods=None, endpoint=None, respond=None, **extra)

Endpoint is a middleware capable to respont to a request.

Enpoint is used by http.bind() methods family to convert middleware’s methods to the middleware’s endpoints. Usually user application never creates enpoints by itself.

See also

Implements: Middleware, Chain, Config

Parameters

respond: coroutine
Coroutine to respond to a request.
extra: dict
Extra arguments.

Examples

Let see how to get access to an endpoint:

class Middleware(Middleware):

    # Public

    @http.get('/<text:path>')
    def echo(self, request, text):
        return http.Response(text=text)

endpoint = Middleware('<service>')['echo']
response = yield from endpoint('<request>')
RESPOND = None

Default respond parameter.

extra

Dict if extra arguments passed to the endpoint.

respond(request, **kwargs)

Respond to a request (coroutine).

Parameters

request: http.Request
Request instance.
kwargs: dict
Keyword arguments.

Returns

object
Reply value.

Router

class interest.Router(service, *, parsers=None)

Router is a component responsible for the routing.

Router’s only two fings to do are to check if request/constraints pair have Match or not and to costruct url back from the middleware name and the given parameters. Router uses Parser dict to handle placeholders in paths. Builtin parsers are liste below.

See also

Implements: Config

Parameters

service: Service
Service instance.
parsers: dict
Dictionary of the Parser sublasses.

Builtin parsers

  • str
  • path
  • int
  • float

Examples

Let’s see how match and url work:

router = Router()
match = router.match('<request>', '/some/path/<name:int>')
url = router.url('name', **match)
PARSERS = {}

Default parsers parameter.

service

Service instance (read-only).

match(request, *, root=None, path=None, methods=None)

Return match or None for the request/constraints pair.

Parameters

request: http.Request
Request instance.
root: str
HTTP path root.
path: str
HTTP path.
methods: list
HTTP methods.

Returns

Match/None
Match instance (True) or None (False).
url(name, *, base=None, query=None, **match)

Construct an url for the given parameters.

Parameters

name: str
Nested middleware’s name separated by dots.
base: Middleware
Base middleware to start searching from.
query: dict
Query string data.
match: dict
Path parameters.

Returns

str
Constructed url.

Parser

class interest.Parser(service, *, pattern=None, convert=None, restore=None)

Parser is a component responsible for the parsing.

Router uses a parsers dictionary to handle user placeholders in paths. Placeholder is a path insertion in following form “<name:parser>”.

See also

Implements: Config

Parameters

service: Service
Service instance.
pattern: str
Regex pattern to match.
convert: callable
Callable to convert a string to a value.
restore: callable
Callable to restore a string from a value.

Examples

Let’s create a binary parser:

class BinaryParser(Parser):

    # Public

    PATTERN = r'[01]+'
    CONVERT = int

router = Router(parsers={'bin': BinaryParser})
router.match('<request>', '/some/path/<name:bin>')
PATTERN = None

Default pattern parameter.

CONVERT

Default convert parameter.

alias of str

RESTORE

Default restore parameter.

alias of str

service

Service instance (read-only).

pattern

Parser’s pattern (read-only).

convert(string)

Convert a given string to a value.

Parameters

string: str
String to convert.

Returns

object
Converted string.
restore(value)

Restore a given value to a string.

Parameters

value: object
Value to restore.

Returns

str
Restored string.

Logger

class interest.Logger(service, *, system=None, template=None)

Logger is a component responsible for the logging.

Logger provides standard log methods named after level and access method to log access’ Record instances.

See also

Implements: Config

Parameters

service: Service
Service instance.
system: object
System logger instance.
template: str
Template for access formatting.

Examples

For production use let’s print the access log to the stdout and skip the debug log at all:

class ProductionLogger(Logger):

    # Public

    SYSTEM = logging.getLogger('myapp')
    TEMPLATE = '%(host)s %(time)s and so on'

    def access(self, record):
        print(self.template % record)

    def debug(self, message, *args, **kwargs):
        pass

logger = ProductionLogger()
SYSTEM = <logging.Logger object>

Default system parameter.

TEMPLATE = '%(host)s %(time)s "%(request)s" %(status)s %(length)s "%(referer)s" "%(agent)s"'

Default template parameter.

service

Service instance (read-only).

system

System logger (read-only).

template

Template for access formatting (read-only).

access(record)

Log access event.

Parameters

record: Record
Record dict to use with template.
debug(message, *args, **kwargs)

Log debug event.

Compatible with logging.debug signature.

info(message, *args, **kwargs)

Log info event.

Compatible with logging.info signature.

warning(message, *args, **kwargs)

Log warning event.

Compatible with logging.warning signature.

error(message, *args, **kwargs)

Log error event.

Compatible with logging.error signature.

exception(message, *args, **kwargs)

Log exception event.

Compatible with logging.exception signature.

critical(message, *args, **kwargs)

Log critical event.

Compatible with logging.critical signature.

Handler

class interest.Handler(service, *, connection_timeout=None, request_timeout=None)

Handler is a component responsible for the request handling.

Handler handles requests on low-level. Handler is asyncio.Protocol implementation derived from the aiohttp’s aiohttp.server.ServerHttpProtocol.

See also

Implements: Config

Parameters

service: Service
Service instance.
connection_timeout: int
Time to keep connection opened in seconds.
request_timeout: int
Slow request timeout in seconds.

Example

Let’s create a handler and then an asyncio server:

# Create handler
handler = Handler(
    '<service>', connection_timeout=25, request_timeout=5)

# Create server
loop = asyncio.get_event_loop()
server = loop.create_server(handler.fork)
server = self.loop.run_until_complete(server)
CONNECTION_TIMEOUT = 75

Time to keep connection opened in seconds (default).

REQUEST_TIMEOUT = 15

Slow request timeout in seconds (default).

service

Service instance (read-only).

fork()

Handler factory for asyncio’s loop.create_server.

Record

class interest.Record(*, request, response, transport, duration)

Record is a safe dictionary with data about request handling.

Record object represents interaction between Handler and client as dict ready to use with text templates. Dict is safe. If key is missing client gets ‘-‘ symbol. All values are strings. See available items below.

See also

Implements: dict

Parameters

Warning

Parameters are not a part of the public API.

Items

agent: str
Client’s agent representation.
duration: str
Handling duration in mileseconds.
host: str
Client remote adress.
lenght: str
Response length in bytes.
process: str
Process identifier.
referer: str
Client’s referer representation.
request: str
Client’s request representation.
status: str
Response status.
time: str
Time when handling have been done (GMT).
<key:req>: str
Request’s header by key.
<key:res>: str
Response’s header by key.

Example

Usually we have Intercation instance in Logger.access() call. Imagine our interactive console works in context of this method:

>>> record['host']
'127.0.0.1',
>>> record['length']
'193'
>>> record['<content-type:res>']
'application/json; charset=utf-8'

Notes

Safe dict idea with random access to request/respones headers is borrowed from Gunicorn/aiohttp libraries.

Provider

class interest.Provider(service, *, provide=None)

Provider is a extended coroutine to update the service.

Parameters

service: Service
Service instance.
provide: coroutine
Coroutine for actual work.
PROVIDE = None

Default provide parameter.

__call__(service)

Update the service.

Parameters

service: Service
Service instance.
service

Service instance (read-only).

provide(service)

Update the service.

Parameters

service: Service
Service instance.

Chain

class interest.Chain(*args, **kwargs)

Chain is a enhanced sequence.

push(item, *, index=None)

Push item to the chain.

pull(*, index=None)

Pull item from the chain.

Config

class interest.Config

Config is a interface to fork classes.

classmethod config(**defaults)

Return config with updated defaults.

Parameters

defaults: dict
Defaults values.

Returns

Config
Config with updated defaults.

Match

class interest.Match

Match is a dictionary which always resolves to True in boolean context.

See also

Implements: dict

Adapter

class interest.Adapter(*args, *, factory, **kwargs)

Adapter is a middleware to use aiohttp.web’s middleware factories.

See also

Implements: Middleware Chain, Config

Parameters

factory: coroutine
aiohttp.web’s middleware factoriy.

Tester

class interest.Tester(factory, *, loop=None, python=None, environ=None, scheme=None, host=None, port=None)

Tester is a teststand to test interest servers.

Parameters

loop: object
Custom asyncio’s loop.
python: type
Python interpreter for subprocess.
environ: dic
Environ update for subprocess.
scheme: str
Scheme for requests.
host: str
Host to listen on.
port: int
Port to listen on.
LOOP

Default loop parameter.

PYTHON

Default python parameter.

ENVIRON = {}

Default environ parameter.

SCHEME = 'http'

Default scheme parameter.

HOST = '127.0.0.1'

Default host parameter.

PORT

Default port parameter.

http

class interest.http

HTTP library/proxy backed by aiohttp.web.

Part of the documetation is loaded from aiohttp package by Sphinx.

Note

© Copyright 2013, 2014, 2015, KeepSafe.

class Request(app, message, payload, transport, reader, writer, *, _HOST='HOST')

Request.

GET

A multidict with all the variables in the query string.

Lazy property.

POST

A multidict with all the variables in the POST parameters.

post() methods has to be called before using this attribute.

app

Application instance.

content

Return raw payload stream.

cookies

Return request cookies.

A read-only dictionary-like object.

headers

A case-insensitive multidict with all headers.

Lazy property.

host

Read only property for getting HOST header of request.

Returns str or None if HTTP request has no HOST header.

json(*, loader=<function loads>)

Return BODY as JSON.

keep_alive

Is keepalive enabled by client?

match_info

Result of route resolving.

method

Read only property for getting HTTP method.

The value is upper-cased str like ‘GET’, ‘POST’, ‘PUT’ etc.

path

The URL including PATH INFO without the host or scheme.

E.g., /app/blog

path_qs

The URL including PATH_INFO and the query string.

E.g, /app/blog?id=10

payload

Return raw payload stream.

post()

Return POST parameters.

query_string

The query string in the URL.

E.g., id=10

read()

Read request body if present.

Returns bytes object with full request content.

release()

Release request.

Eat unread part of HTTP BODY if present.

text()

Return BODY as text using encoding from .charset.

transport

Transport used for request processing.

version

Read only property for getting HTTP version of request.

Returns aiohttp.protocol.HttpVersion instance.

class http.StreamResponse(*, status=200, reason=None, headers=None)

Stream response.

Delete cookie.

Creates new empty expired cookie.

enable_chunked_encoding(chunk_size=None)

Enables automatic chunked transfer encoding.

enable_compression(force=False)

Enables response compression with deflate encoding.

Set or update response cookie.

Sets new cookie or updates existent with new value. Also updates only those params which are not None.

class http.Response(*, body=None, status=200, reason=None, text=None, headers=None, content_type=None)

Response.

class http.WebSocketResponse(*, timeout=10.0, autoclose=True, autoping=True, protocols=())

WebSocket response.

http.Exception

Exception.

alias of HTTPException

http.Successful

2xx Successful.

alias of HTTPSuccessful

http.Ok

200 OK.

alias of HTTPOk

http.Created

201 Created.

alias of HTTPCreated

http.Accepted

202 Accepted.

alias of HTTPAccepted

http.NonAuthoritativeInformation

203 Non-Authoritative Information.

alias of HTTPNonAuthoritativeInformation

http.NoContent

204 No Content.

alias of HTTPNoContent

http.ResetContent

205 Reset Content.

alias of HTTPResetContent

http.PartialContent

206 Partial Content.

alias of HTTPPartialContent

http.Redirection

3xx Redirection.

alias of HTTPRedirection

http.MultipleChoices

300 Multiple Choices.

alias of HTTPMultipleChoices

http.MovedPermanently

301 Moved Permanently.

alias of HTTPMovedPermanently

http.Found

302 Found.

alias of HTTPFound

http.SeeOther

303 See Other.

alias of HTTPSeeOther

http.NotModified

304 Not Modified.

alias of HTTPNotModified

http.UseProxy

305 Use Proxy.

alias of HTTPUseProxy

http.TemporaryRedirect

307 Temporary Redirect.

alias of HTTPTemporaryRedirect

http.Error

4/5xx Client or Server Error.

alias of HTTPError

http.ClientError

4xx Client Error.

alias of HTTPClientError

http.BadRequest

400 Bad Request.

alias of HTTPBadRequest

http.Unauthorized

401 Unauthorized.

alias of HTTPUnauthorized

http.PaymentRequired

402 Payment Required.

alias of HTTPPaymentRequired

http.Forbidden

403 Forbidden.

alias of HTTPForbidden

http.NotFound

404 Not Found.

alias of HTTPNotFound

http.MethodNotAllowed

405 Method Not Allowed.

alias of HTTPMethodNotAllowed

http.NotAcceptable

406 Not Acceptable.

alias of HTTPNotAcceptable

http.ProxyAuthenticationRequired

407 Proxy Authentication Required.

alias of HTTPProxyAuthenticationRequired

http.RequestTimeout

408 Request Timeout.

alias of HTTPRequestTimeout

http.Conflict

409 Conflict.

alias of HTTPConflict

http.Gone

410 Gone.

alias of HTTPGone

http.LengthRequired

411 Length Required.

alias of HTTPLengthRequired

http.PreconditionFailed

412 Precondition Failed.

alias of HTTPPreconditionFailed

http.RequestEntityTooLarge

413 Request Entity Too Large.

alias of HTTPRequestEntityTooLarge

http.RequestURITooLong

414 Request-URI Too Long.

alias of HTTPRequestURITooLong

http.UnsupportedMediaType

415 Unsupported Media Type.

alias of HTTPUnsupportedMediaType

http.RequestRangeNotSatisfiable

416 Requested Range Not Satisfiable.

alias of HTTPRequestRangeNotSatisfiable

http.ExpectationFailed

417 Expectation Failed.

alias of HTTPExpectationFailed

http.ServerError

5xx Server Error.

alias of HTTPServerError

http.InternalServerError

500 Internal Server Error.

alias of HTTPInternalServerError

http.NotImplemented

501 Not Implemented.

alias of HTTPNotImplemented

http.BadGateway

502 Bad Gateway.

alias of HTTPBadGateway

http.ServiceUnavailable

503 Service Unavailable.

alias of HTTPServiceUnavailable

http.GatewayTimeout

504 Gateway Timeout.

alias of HTTPGatewayTimeout

http.VersionNotSupported

505 HTTP Version Not Supported.

alias of HTTPVersionNotSupported

classmethod http.bind(param=None, **kwargs)

Bind middleware’s method as endpoint.

classmethod http.options(param=None, **kwargs)

Bind middleware’s method as OPTIONS endpoint.

classmethod http.get(param=None, **kwargs)

Bind middleware’s method as GET endpoint.

classmethod http.head(param=None, **kwargs)

Bind middleware’s method as HEAD endpoint.

classmethod http.post(param=None, **kwargs)

Bind middleware’s method as POST endpoint.

classmethod http.put(param=None, **kwargs)

Bind middleware’s method as PUT endpoint.

classmethod http.delete(param=None, **kwargs)

Bind middleware’s method as DELETE endpoint.

classmethod http.patch(param=None, **kwargs)

Bind middleware’s method as PATCH endpoint.

version

interest.version

Current version.