2018-03-20 17:13:07 +00:00
|
|
|
"""
|
|
|
|
Handy utils.
|
|
|
|
"""
|
|
|
|
import json
|
|
|
|
import asks
|
|
|
|
import logging
|
|
|
|
|
|
|
|
from ..log import colorize_json
|
|
|
|
|
|
|
|
|
|
|
|
class BrokerError(Exception):
|
|
|
|
"Generic broker issue"
|
|
|
|
|
|
|
|
|
2020-05-18 00:39:38 +00:00
|
|
|
class SymbolNotFound(BrokerError):
|
|
|
|
"Symbol not found by broker search"
|
|
|
|
|
|
|
|
|
2018-03-20 17:13:07 +00:00
|
|
|
def resproc(
|
|
|
|
resp: asks.response_objects.Response,
|
|
|
|
log: logging.Logger,
|
|
|
|
return_json: bool = True
|
|
|
|
) -> asks.response_objects.Response:
|
|
|
|
"""Process response and return its json content.
|
|
|
|
|
|
|
|
Raise the appropriate error on non-200 OK responses.
|
|
|
|
"""
|
|
|
|
if not resp.status_code == 200:
|
|
|
|
raise BrokerError(resp.body)
|
|
|
|
try:
|
2019-02-24 15:55:52 +00:00
|
|
|
json = resp.json()
|
2018-03-20 17:13:07 +00:00
|
|
|
except json.decoder.JSONDecodeError:
|
|
|
|
log.exception(f"Failed to process {resp}:\n{resp.text}")
|
|
|
|
raise BrokerError(resp.text)
|
|
|
|
else:
|
2019-02-24 15:55:52 +00:00
|
|
|
log.trace(f"Received json contents:\n{colorize_json(json)}")
|
2018-03-20 17:13:07 +00:00
|
|
|
|
2019-02-24 15:55:52 +00:00
|
|
|
return json if return_json else resp
|