Skip to content

Instantly share code, notes, and snippets.

@MtkN1
Created July 4, 2023 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MtkN1/6b84d50e516501384bc39539f3d75866 to your computer and use it in GitHub Desktop.
Save MtkN1/6b84d50e516501384bc39539f3d75866 to your computer and use it in GitHub Desktop.
Decimal や datetime の入った JSON 風オブジェクトを loguru 向けにダンプして出力するクラス
"""
Decimal や datetime の入った JSON 風オブジェクトを loguru 向けにダンプして出力するクラス
"""
import datetime
import json
from decimal import Decimal
from typing import Any
import requests
from loguru import logger
from rich.pretty import pprint
class JSONLog:
def __init__(self, message: Any):
self.message = message
@staticmethod
def default(obj: Any):
match obj:
case Decimal():
return float(obj)
case datetime.datetime():
return obj.isoformat()
case _:
return str(obj)
def __str__(self) -> str:
return json.dumps(
self.message, ensure_ascii=False, indent=4, default=self.default
)
r = requests.get("https://api.bitflyer.com/v1/ticker")
ticker = r.json()
for key in ("timestamp",):
ticker[key] = datetime.datetime.fromisoformat(ticker[key])
for key in (
"best_bid",
"best_ask",
"best_bid_size",
"best_ask_size",
"total_bid_depth",
"total_ask_depth",
"market_bid_size",
"market_ask_size",
"ltp",
"volume",
"volume_by_product",
):
ticker[key] = Decimal(str(ticker[key]))
pprint(ticker, indent_guides=False)
""" ※ この形式だと JSON ダンプできない
{
'product_code': 'BTC_JPY',
'state': 'RUNNING',
'timestamp': datetime.datetime(2023, 7, 4, 7, 59, 16, 377000),
'tick_id': 14380026,
'best_bid': Decimal('4481077.0'),
'best_ask': Decimal('4481132.0'),
'best_bid_size': Decimal('0.01'),
'best_ask_size': Decimal('0.022'),
'total_bid_depth': Decimal('636.31801651'),
'total_ask_depth': Decimal('306.85054554'),
'market_bid_size': Decimal('0.0'),
'market_ask_size': Decimal('0.0'),
'ltp': Decimal('4481077.0'),
'volume': Decimal('4011.33397438'),
'volume_by_product': Decimal('1756.56323256')
}
"""
logger.info(JSONLog(ticker))
"""
2023-07-04 16:59:17.139 | INFO | __main__:<module>:78 - {
"product_code": "BTC_JPY",
"state": "RUNNING",
"timestamp": "2023-07-04T07:59:16.377000",
"tick_id": 14380026,
"best_bid": 4481077.0,
"best_ask": 4481132.0,
"best_bid_size": 0.01,
"best_ask_size": 0.022,
"total_bid_depth": 636.31801651,
"total_ask_depth": 306.85054554,
"market_bid_size": 0.0,
"market_ask_size": 0.0,
"ltp": 4481077.0,
"volume": 4011.33397438,
"volume_by_product": 1756.56323256
}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment