server.py (1902B)
1 import re 2 import os 3 import argparse 4 import logging 5 import socket 6 import json 7 8 import websocket 9 10 from gas_proxy.proxy import JSONRPCOracle as Oracle 11 from gas_proxy.cache.mem import MemCache 12 13 logging.basicConfig(level=logging.WARNING) 14 logg = logging.getLogger() 15 16 17 argparser = argparse.ArgumentParser() 18 #argparser.add_argument('-c', type=str, default=config_dir, help='config file') 19 argparser.add_argument('--env-prefix', default=os.environ.get('CONFINI_ENV_PREFIX'), dest='env_prefix', type=str, help='environment prefix for variables to overwrite configuration') 20 argparser.add_argument('--host', default='localhost', type=str) 21 argparser.add_argument('--port', default=8545, type=int) 22 argparser.add_argument('-v', action='store_true', help='be verbose') 23 argparser.add_argument('-vv', action='store_true', help='be more verbose') 24 argparser.add_argument('provider', type=str, help='Gas price provider url') 25 args = argparser.parse_args() 26 27 if args.vv: 28 logging.getLogger().setLevel(logging.DEBUG) 29 elif args.v: 30 logging.getLogger().setLevel(logging.INFO) 31 32 re_websocket = r'^wss?://(.+):(\d+)/?$' 33 m = re.match(re_websocket, args.provider) 34 if m == None: 35 raise ValueError('websocket providers only') 36 37 logg.debug('using websocket host {} port {}'.format(m.group(1), m.group(2))) 38 connection_string = args.provider 39 40 41 def main(): 42 memcache = MemCache() 43 44 ws = websocket.create_connection(connection_string) 45 ws = Oracle(ws, cache=memcache) 46 47 s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 48 s.bind((args.host, args.port)) 49 s.listen(10) 50 51 while True: 52 (csock, caddr) = s.accept() 53 d = csock.recv(4096) 54 o = json.loads(d) 55 response = { 56 "jsonrpc": "2.0", 57 "id": o['id'], 58 "result": ws.get(), 59 } 60 csock.send(json.dumps(response).encode('utf-8')) 61 62 63 if __name__ == '__main__': 64 main()