本文整理匯總了Python中websockets.WebSocketClientProtocol方法的典型用法代碼示例。如果您正苦於以下問題:Python websockets.WebSocketClientProtocol方法的具體用法?Python websockets.WebSocketClientProtocol怎麽用?Python websockets.WebSocketClientProtocol使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類websockets
的用法示例。
在下文中一共展示了websockets.WebSocketClientProtocol方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: build_pipeline
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def build_pipeline(self) -> websockets.WebSocketClientProtocol:
"""Builds a data pipeine for processing data.
Often we want to take the data we are streaming and
use it in other functions or store it in other platforms.
This method makes the process of building a pipeline easy
by handling all the connection setup and request setup.
Returns:
----
websockets.WebSocketClientProtocol -- The websocket connection.
"""
# In this case, we don't want things printing to the console.
self.print_to_console = False
# Connect to Websocket.
await self._connect()
# Build the Data Request.
await self._send_message(self._build_data_request())
return self.connection
示例2: __init__
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def __init__(self, title, url, ws_uri, tab_id):
self.id_ = tab_id
self._title = title
self._url = url
self._ws_uri = ws_uri
self.target_id = ws_uri.split('/')[-1]
self._ws: Optional[websockets.WebSocketClientProtocol] = None
self._message_id = 0
self._current_task: Optional[asyncio.Task] = None
self._ack_events = {}
self._ack_payloads = {}
self._input_events = {}
self._trigger_events = {}
self._event_payloads = {}
self._recv_task = None
self._log = logging.getLogger('chromewhip.chrome.ChromeTab')
self._send_log = logging.getLogger('chromewhip.chrome.ChromeTab.send_handler')
self._recv_log = logging.getLogger('chromewhip.chrome.ChromeTab.recv_handler')
示例3: _reset
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _reset(self) -> None:
self._ws_task: Optional[Future] = None
self._futures: Dict[int, Future] = {}
self._callbacks: Dict[str, Callable[[Dict], Any]] = {}
self.websocket: Optional[websockets.WebSocketClientProtocol] = None
self._request_id: int = 0
self._render_future = self.loop.create_future()
self._mhtml = MHTML()
self._requests_sent: int = 0
self._responses_received: Dict = {}
self._res_body_request_ids: Dict = {}
self._last_active_time: float = 0
self._url: Optional[str] = None
self._intercept_requests: bool = False
self._proxy: str = ''
示例4: _inner_messages
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _inner_messages(self,
ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
if ((msg != "{\"event\":\"heartbeat\"}" and
"\"event\":\"systemStatus\"" not in msg and
"\"event\":\"subscriptionStatus\"" not in msg)):
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
示例5: listen_for_trades
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
while True:
try:
ws_message: str = await self.get_ws_subscription_message("trade")
async with websockets.connect(DIFF_STREAM_URL) as ws:
ws: websockets.WebSocketClientProtocol = ws
await ws.send(ws_message)
async for raw_msg in self._inner_messages(ws):
msg: List[Any] = ujson.loads(raw_msg)
trades: List[Dict[str, Any]] = [{"pair": msg[-1], "trade": trade} for trade in msg[1]]
for trade in trades:
trade_msg: OrderBookMessage = KrakenOrderBook.trade_message_from_exchange(trade)
output.put_nowait(trade_msg)
except asyncio.CancelledError:
raise
except Exception:
self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...",
exc_info=True)
await asyncio.sleep(30.0)
示例6: _inner_messages
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _inner_messages(self,
ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
# get required data to create a websocket request
示例7: _inner_messages
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
self._last_recv_time = time.time()
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
self._last_recv_time = time.time()
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except websockets.exceptions.ConnectionClosed:
return
finally:
await ws.close()
示例8: _inner_messages
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _inner_messages(self,
ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
示例9: listen_for_trades
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def listen_for_trades(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
while True:
try:
trading_pairs: List[str] = await self.get_trading_pairs()
ws_path: str = "/".join([f"{trading_pair.lower()}@trade" for trading_pair in trading_pairs])
stream_url: str = f"{DIFF_STREAM_URL}/{ws_path}"
async with websockets.connect(stream_url) as ws:
ws: websockets.WebSocketClientProtocol = ws
async for raw_msg in self._inner_messages(ws):
msg = ujson.loads(raw_msg)
trade_msg: OrderBookMessage = BinanceOrderBook.trade_message_from_exchange(msg)
output.put_nowait(trade_msg)
except asyncio.CancelledError:
raise
except Exception:
self.logger().error("Unexpected error with WebSocket connection. Retrying after 30 seconds...",
exc_info=True)
await asyncio.sleep(30.0)
示例10: listen_for_user_stream
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
while True:
try:
ws: websockets.WebSocketClientProtocol
async with websockets.connect(BITFINEX_WS_URI) as ws:
ws: websockets.WebSocketClientProtocol = ws
payload = self._bitfinex_auth.generate_auth_payload()
await ws.send(json.dumps(payload))
async for raw_msg in self._get_response(ws):
transformed_msg: BitfinexOrderBookMessage = self._transform_message_from_exchange(raw_msg)
if transformed_msg:
output.put_nowait(transformed_msg)
except asyncio.CancelledError:
raise
except Exception:
self.logger().error(
"Unexpected error with Bitfinex WebSocket connection. " "Retrying after 30 seconds...",
exc_info=True,
)
await asyncio.sleep(self.MESSAGE_TIMEOUT)
示例11: _get_response
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _get_response(self, ws: websockets.WebSocketClientProtocol):
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
self._last_recv_time = time.time()
yield msg
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
示例12: __init__
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def __init__(self, channel, rs_target):
scheme = 'wss' if ('https://' in rs_target) else 'ws'
netloc = parse.urlparse(rs_target).netloc
self._target_uri = f"{scheme}://{netloc}/api/ws/{channel}"
self._exception = None
self._websocket: WebSocketClientProtocol = None
self._subscribe_event: Event = None
ws_methods.add(self.node_ws_PublishHeartbeat)
ws_methods.add(self.node_ws_PublishNewBlock)
logging.debug(f"websocket target uri : {self._target_uri}")
示例13: _prepare_connection
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _prepare_connection(self):
self._websocket: WebSocketClientProtocol = await websockets.connect(
uri=self._target_uri,
max_size=4 * conf.MAX_TX_SIZE_IN_BLOCK,
loop=MessageQueueService.loop
)
示例14: _connect
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def _connect(self, pipeline_start: bool = True) -> websockets.WebSocketClientProtocol:
"""Connects the Client to the TD Websocket.
Connecting to webSocket server websockets.client.connect
returns a WebSocketClientProtocol, which is used to send
and receive messages
Keyword Arguments:
----
pipeline_start {bool} -- This is also used to start the data
pipeline so, in that case we can handle more tasks here.
(default: {True})
Returns:
---
websockets.WebSocketClientProtocol -- The websocket connection.
"""
# Grab the login info.
login_request = self._build_login_request()
# Create a connection.
self.connection = await websockets.client.connect(self.websocket_url)
# check it before sending it back.
if await self._check_connection() and pipeline_start == True:
# Login to the stream.
await self._send_message(login_request)
await self._receive_message(return_value=True)
return self.connection
else:
# Login to the stream.
await self._send_message(login_request)
await self._receive_message(return_value=False)
return self.connection
示例15: acquire
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import WebSocketClientProtocol [as 別名]
def acquire(self) -> WebSocketClientProtocol:
while True:
try:
sock = self._freepool.pop()
if sock.closed:
await sock.close()
continue
if self.initsize > len(self._freepool):
asyncio.create_task(self._create())
return sock
except KeyError:
await self._create()