python: fix utils

This commit is contained in:
なるみ 2022-04-18 11:45:03 +08:00
parent 17ce9fa90b
commit 715b2bb4cc
4 changed files with 70 additions and 0 deletions

View File

@ -1,4 +1,5 @@
from . import enums from . import enums
from . import utils
from .services import MarketService from .services import MarketService
from .services import TradingService from .services import TradingService
from .services import UserDataService from .services import UserDataService

View File

@ -0,0 +1,7 @@
from .convert import parse_float
from .convert import parse_time
from .grpc_utils import get_credentials_from_env
from .grpc_utils import get_grpc_cert_file_from_env
from .grpc_utils import get_grpc_key_file_from_env
from .grpc_utils import get_insecure_channel
from .grpc_utils import get_insecure_channel_from_env

View File

@ -0,0 +1,19 @@
from datetime import datetime
from typing import Union
def parse_float(s: str) -> float:
if s is None:
return 0
if s == "":
return 0
return float(s)
def parse_time(t: Union[str, int]) -> datetime:
if isinstance(t, str):
t = int(t)
return datetime.fromtimestamp(t / 1000),

View File

@ -0,0 +1,43 @@
import os
import grpc
def read_binary(f):
with open(f, 'rb') as fp:
return fp.read()
def get_grpc_cert_file_from_env():
cert_file = os.environ.get('BBGO_GRPC_CERT_FILE')
return cert_file
def get_grpc_key_file_from_env():
key_file = os.environ.get('BBGO_GRPC_KEY_FILE')
return key_file
def get_credentials_from_env():
key_file = get_grpc_key_file_from_env()
private_key = read_binary(key_file)
cert_file = get_grpc_cert_file_from_env()
certificate_chain = read_binary(cert_file)
private_key_certificate_chain_pairs = [(private_key, certificate_chain)]
server_credentials = grpc.ssl_server_credentials(private_key_certificate_chain_pairs)
return server_credentials
def get_insecure_channel(host: str, port: int) -> grpc.Channel:
address = f'{host}:{port}'
return grpc.insecure_channel(address)
def get_insecure_channel_from_env() -> grpc.Channel:
host = os.environ.get('BBGO_GRPC_HOST') or '127.0.0.1'
port = os.environ.get('BBGO_GRPC_PORT') or 50051
address = get_insecure_channel(host, port)
return grpc.insecure_channel(address)