Add an `api` cli subcommand for console testing

Add `piker api <method> <kwargs>` for easy testing of the
underlying broker api from the console.
kivy_mainline_and_py3.8
Tyler Goodlet 2018-01-26 14:31:15 -05:00
parent 27a39ac3ad
commit 1b93a4c02a
1 changed files with 42 additions and 11 deletions

View File

@ -1,24 +1,26 @@
"""
Console interface to broker client/daemons.
"""
import importlib
from pprint import pformat
import json
from functools import partial
from importlib import import_module
import click
import trio
from ..log import get_console_log
from ..log import get_console_log, colorize_json
def run(loglevel, main):
def run(main, loglevel='info'):
log = get_console_log(loglevel)
# main loop
# main sandwich
try:
client = trio.run(main)
return trio.run(main)
except Exception as err:
log.exception(err)
else:
log.debug(
f"Exiting with last access info:\n{pformat(client.access_data)}\n")
finally:
log.debug("Exiting pikerd")
@click.command()
@ -26,5 +28,34 @@ def run(loglevel, main):
@click.option('--loglevel', '-l', default='info', help='Logging level')
def pikerd(broker, loglevel):
# import broker module daemon entry point
brokermod = importlib.import_module('.' + broker, 'piker.brokers')
run(loglevel, brokermod.serve_forever)
brokermod = import_module('.' + broker, 'piker.brokers')
run(brokermod.serve_forever, loglevel)
@click.group()
def cli():
pass
@cli.command()
@click.option('--broker', default='questrade', help='Broker backend to use')
@click.option('--loglevel', '-l', default='warning', help='Logging level')
@click.argument('meth', nargs=1)
@click.argument('kwargs', nargs=-1, required=True)
def api(meth, kwargs, loglevel, broker):
"""Client for testing broker API methods with pretty printing of output.
"""
log = get_console_log(loglevel)
brokermod = import_module('.' + broker, 'piker.brokers')
_kwargs = {}
for kwarg in kwargs:
if '=' not in kwarg:
log.error(f"kwarg `{kwarg}` must be of form <key>=<value>")
else:
key, _, value = kwarg.partition('=')
_kwargs[key] = value
data = run(partial(brokermod.api, meth, **_kwargs), loglevel=loglevel)
if data:
click.echo(colorize_json(data))