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.
Fixtures¶
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.
Parameters: -
create_url
(url)¶
-
request
(method, url, *args, raise_for_status=None, **kwargs)¶ Constructs a
Request
, prepares it and sends it. ReturnsResponse
object.Parameters: - 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 toFalse
, 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 toFalse
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: - method – method for the new
-
-
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 aRuntimeError
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.
Example
from sqlalchemy import create_engine from krake.fixtures import fixture, depends, Resolver @fixture def engine(): yield create_engine("postgresql://user:passwd@localhost:5432/database") @depends("engine") 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: print(row["username"]) 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
-
rok.fixtures.
config
()¶
-
rok.fixtures.
depends
(*dependencies)¶ Decorator function for marking fixture dependencies of a function.
Example
from rok.fixtures import fixture, depends @depends("engine") def fetch_records(engine): # Do something with the engine ... # Fixtures themselves can also depend on other fixtures @fixture @depends("config") def engine(config): return create_engine(config=config) @fixture def config: return load_config()
Parameters: *dependencies – Fixtures the decorated function depends on Returns: Decorator for explicitly marking function dependencies. Return type: callable
-
rok.fixtures.
fixture
(func)¶ 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:
@fixture def session(): with Session() as session: yield session
Parameters: func – Function that should be registered as fixture Raises: RuntimeError
– If the a fixtures with the same name is already registered.
-
rok.fixtures.
session
(config)¶
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.Example
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.Example
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): print(message) parser = spec.create_parser() args = parser.parse_args()
Specifications can be nested:
eggs = ParserSpec("eggs", aliases=["eg"], help="... and eggs") @eggs.command("spam") def eggs_spam(): while True: print("spam") print("eggs") spec.add_spec(eggs)
Parameters: - *args – Positional arguments that will be passed to either
argparse.ArgumentParser
or subparsers. - *kwargs – Keyword arguments that will be passed to either
argparse.ArgumentParser
or subparsers.
-
add_spec
(subparser)¶ 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.
Parameters: - 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
Returns: Decorator for functions that will be registered as
command
default argument on the subparser.Return type: callable
-
create_parser
(parent=None)¶ 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()
Parameters: - *args – Positional arguments for the specification
- **kwargs – Keyword arguments for the specification
Returns: The new subspecification for subcommands
Return type:
- *args – Positional arguments that will be passed to either
-
class
rok.parser.
StoreDict
(option_strings, dest, nargs=None, metavar='KEY=VALUE', **kwargs)¶ Bases:
argparse.Action
Action storing <key=value> pairs in a dictionary.
Example
parser = argparse.ArgumentParser() parser.add_argument( '--foo', action=StoreDict ) args = parser.parse_args('--foo label=test --foo lorem=ipsum') assert argparse.Namespace(foo={'label': 'test', 'lorem': 'ipsum'}) == args
-
rok.parser.
arg_backoff
(fn)¶
-
rok.parser.
arg_backoff_delay
(fn)¶
-
rok.parser.
arg_backoff_limit
(fn)¶
-
rok.parser.
arg_formatting
(fn)¶
-
rok.parser.
arg_global_metric
(fn)¶
-
rok.parser.
arg_labels
(fn)¶
-
rok.parser.
arg_metric
(fn)¶
-
rok.parser.
arg_namespace
(fn)¶
-
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.Parameters: - *args – Positional arguments that should be passed to
argparse.ArgumentParser.add_argument()
. - **kwargs – Keyword arguments that should be passed to
argparse.ArgumentParser.add_argument()
.
Returns: A decorator that can be used to decorate a command function.
Return type: callable
- *args – Positional arguments that should be passed to
-
rok.parser.
mutually_exclusive_group
(group)¶ 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