Client Reference

rok is a Python command line interface for the krake API server. It can be used to manipulate any RESTful resource handled by Krake. It can be used by end users as well as for administrative tasks.


Simple dependency injection module for rok inspired by pytest’s fixtures.

There is a simple registration decorator fixture() that can be used to mark functions as fixtures. Functions using these fixtures can declare their dependency with the use() decorator. Finally, Resolver is used to wire fixtures and dependencies.

class rok.fixtures.BaseUrlSession(base_url=None, raise_for_status=True, client_ca=None, ssl_cert=None, ssl_key=None)

Bases: requests.sessions.Session

Simple requests session using a base URL for all requests.

  • base_url (str, optional) – Base URL that should be used as prefix for every request.
  • raise_for_status (bool, optional) – Automatically raise an exception of for error response codes. Default: True
request(method, url, *args, raise_for_status=None, **kwargs)

Constructs a Request, prepares it and sends it. Returns Response object.

  • method – method for the new Request object.
  • url – URL for the new Request object.
  • params – (optional) Dictionary or bytes to be sent in the query string for the Request.
  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
  • json – (optional) json to send in the body of the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) Dict or CookieJar object to send with the Request.
  • files – (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.
  • auth – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.
  • timeout (float or tuple) – (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.
  • allow_redirects (bool) – (optional) Set to True by default.
  • proxies – (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy.
  • stream – (optional) whether to immediately download the response content. Defaults to False.
  • verify – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True. When set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to False may be useful during local development or testing.
  • cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
Return type:


class rok.fixtures.Resolver(fixtures=None)

Bases: object

Dependency resolver for function arguments annotated with depends().

Dependencies of a function are loaded from the depends attribute of the function. If a fixture is not available, the resolver checks if there is a default argument. Otherwise a RuntimeError is raised.

All fixtures can be overwritten by passing a corresponding keyword argument to the resolver call.

Resolver uses the context manager protocol to manage the lifecycle of generator-based fixtures.


from sqlalchemy import create_engine
from krake.fixtures import fixture, depends, Resolver

def engine():
    yield create_engine("postgresql://user:passwd@localhost:5432/database")

def fetch(engine, min_uid):
    with engine.begin() as connection:
        result = connection.execute(
            "SELECT username FROM users WHERE uid >= ?", min_uid
        for row in result:

with Resolver() as resolver:
    # Execute function "fetch" with resolved fixtures. Additional
    # keyword arguments can be passed. These can also be used to
    # overwrite fixtures.
    resolver(fetch, min_uid=1000)
Parameters:fixtures (dict, optional) – A mapping of fixture names to functions. Defaults to the mapping of fixture.mapping

Decorator function for marking fixture dependencies of a function.


from rok.fixtures import fixture, depends

def fetch_records(engine):
    # Do something with the engine ...

# Fixtures themselves can also depend on other fixtures
def engine(config):
    return create_engine(config=config)

def config:
    return load_config()
Parameters:*dependencies – Fixtures the decorated function depends on
Returns:Decorator for explicitly marking function dependencies.
Return type:callable

Mark a function or generator as fixtures. The name of the function is used as fixture name.

If the marked function is a generator function, the fixture can be used as kind of context manager:

def session():
    with Session() as session:
        yield session

Mapping of registered fixture names to functions

Parameters:func – Function that should be registered as fixture
Raises:RuntimeError – If the a fixtures with the same name is already registered.

Command Line Parser

This module defines a declarative API for Python’s standard argparse module.

class rok.parser.MetricAction(*args, nargs=None, default=None, metavar=None, **kwargs)

Bases: argparse.Action

argparse action for metric values

A metric argument requires two arguments. The first argument is the name of a metric (str). The second argument is the weight of the argument as float. The option can be called several times.


cli --metric-argument my-metric 1.2 --metric-argument my-other-metric 4.5

The action will populate the namespace with a list of dictionaries:

    {"name": "my-metric", "weight": 1.2},
    {"name": "my-other-metric", "weight": 4.5},
class rok.parser.ParserSpec(*args, **kwargs)

Bases: object

Declarative parser specification for Python’s standard argparse module.


from rok.parser import ParserSpec, argument

spec = ParserSpec(prog="spam", description="Spam command line interface")

@spec.command("spam", help="Spam your shell")
@argument("-n", type=int, default=42, help="How often should I spam?")
@argument("message", help="Spam message")
def spam(n, message):
    for _ in range(n):

parser = spec.create_parser()
args = parser.parse_args()

Specifications can be nested:

eggs = ParserSpec("eggs", aliases=["eg"], help="... and eggs")

def eggs_spam():
    while True:


Register another specification as subparser

Parameters:subparser (ParserSpec) – Sub-specification defining subcommands
command(name, *args, **kwargs)

Decorator function for commands registering the name, positional and keyword arguments for a subparser.

  • name (name) – Name of the command that will be used in the command line.
  • *args – Positional arguments for the subparser
  • **kwargs – Keyword arguments for the subparser

Decorator for functions that will be registered as command default argument on the subparser.

Return type:



Create a standard Python parser from the specification

Parameters:parent (optional) – argparse subparser that should be used instead of creating a new root argparse.ArgumentParser
Returns:Standard Python parser
Return type:argparse.ArgumentParser
subparser(*args, **kwargs)

Create a subspecification and automatically register it via add_spec()

  • *args – Positional arguments for the specification
  • **kwargs – Keyword arguments for the specification

The new subspecification for subcommands

Return type:


class rok.parser.StoreDict(option_strings, dest, nargs=None, metavar='KEY=VALUE', **kwargs)

Bases: argparse.Action

Action storing <key=value> pairs in a dictionary.


parser = argparse.ArgumentParser()
    '--foo', action=StoreDict
args = parser.parse_args('--foo label=test --foo lorem=ipsum')
assert argparse.Namespace(foo={'label': 'test', 'lorem': 'ipsum'}) == args
rok.parser.argument(*args, **kwargs)

Decorator function for standard argparse arguments.

The passed arguments and keyword arguments are stored as tuple in a parser_arguments attribute of the decorated function. This list will be reused by class:ParserSpec to add arguments to decorated commands.


A decorator that can be used to decorate a command function.

Return type:



Decorator function for mutually exclusive argparse arguments.

Parameters:group (list of tuples) – A list of the standard :mod: argparse arguments which are mutually exclusive. Each argument is represented as a tuple of its args and kwargs.
Returns:A decorator that can be used to decorate a command function.
Return type:callable