本文整理汇总了Python中websocket.create_connection方法的典型用法代码示例。如果您正苦于以下问题:Python websocket.create_connection方法的具体用法?Python websocket.create_connection怎么用?Python websocket.create_connection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类websocket
的用法示例。
在下文中一共展示了websocket.create_connection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ws
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def ws(url, callback, json=False, wrap=False):
'''Connect to websocket and pipe results through the callback
Args:
url (str): websocket url to connect to
callback (callable): function to call on websocket data
json (bool): load websocket data as json
wrap (bool): wrap result in a list
'''
ws = create_connection(url)
for x in run(ws.recv):
if isinstance(x, StreamNone):
continue
elif not x or isinstance(x, StreamEnd):
break
if json:
x = load_json(x)
if wrap:
x = [x]
callback(x)
示例2: reconnect
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def reconnect(self):
"""重连"""
try:
if self.DEBUG:
print('DataApi:reconnect:{}'.format(self.url))
if not self.proxyHost:
self.ws = create_connection(self.url)
else:
self.ws = create_connection(self.url,
http_proxy_host=self.proxyHost,
http_proxy_port=self.proxyPort)
return True
except:
msg = traceback.format_exc()
self.onError(u'行情服务器重连失败:%s' %msg)
return False
#----------------------------------------------------------------------
示例3: _recv_msg
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def _recv_msg(self, message: bin) -> bin:
"""Forwards a message to the WebsocketServerWorker"""
response = self._forward_to_websocket_server_worker(message)
if not self.ws.connected:
logger.warning("Websocket connection closed (worker: %s)", self.id)
self.ws.shutdown()
time.sleep(0.1)
# Avoid timing out on the server-side
self.ws = websocket.create_connection(self.url, max_size=None, timeout=self.timeout)
logger.warning("Created new websocket connection")
time.sleep(0.1)
response = self._forward_to_websocket_server_worker(message)
if not self.ws.connected:
raise RuntimeError(
"Websocket connection closed and creation of new connection failed."
)
return response
示例4: _socket_create_connection
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def _socket_create_connection(self, stream_url):
ws = None
try:
ws = websocket.create_connection(stream_url,
timeout=self.timeout)
except ValueError:
with excutils.save_and_reraise_exception():
LOG.error("websocket create connection invalid URL")
except Exception:
# Although a number of exceptions can occur here
# we handle them all the same way, return None.
# As such, enough to just "except Exception."
LOG.exception("websocket create connection failed",
exc_info=True)
return None
if ws is None or not ws.connected:
LOG.error("websocket create connection unsuccessful")
return None
LOG.debug("websocket connection established")
return ws
示例5: __init__
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def __init__(self, config):
import websocket
self.token_file = os.path.dirname(os.path.realpath(__file__)) + "/" + config["mac_address"]
if not config["port"]:
config["port"] = 8001
if "timeout" not in config or ("timeout" in config and config["timeout"] == 0):
config["timeout"] = None
if config["port"] == 8002:
url = SSL_URL_FORMAT.format(config["host"], config["port"],
self._serialize_string(config["name"]))
if os.path.isfile(self.token_file):
with open(self.token_file, "r") as token_file:
url += "&token=" + token_file.readline()
else:
config["timeout"] = 10
self.connection = websocket.create_connection(url, config["timeout"], sslopt={"cert_reqs": ssl.CERT_NONE})
else:
url = URL_FORMAT.format(config["host"], config["port"],
self._serialize_string(config["name"]))
self.connection = websocket.create_connection(url, config["timeout"])
self._read_response()
示例6: find_sent_link_with_priority
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def find_sent_link_with_priority(cls, d_list, top_k=5, predict=False):
ws_second = websocket.create_connection(cls.second_round_path)
for i in spcl(range(len(d_list))):
ws_second.send(json.dumps(d_list[i]))
item = json.loads(ws_second.recv())
pids = [it[0] for it in item['prioritized_docids']]
item['prioritized_docids_aside'] = \
[it for it in item['prioritized_docids_aside']\
if it[0] not in pids]
if predict:
porg = \
set([k for k, v \
in sorted(item['prioritized_docids'],
key=lambda x: (-x[1], x[0]))][:top_k])
paside = \
set([k for k, v \
in sorted(item['prioritized_docids_aside'],
key=lambda x: (-x[1], x[0]))][:top_k])
item['predicted_docids'] = list(porg | paside)
item['predicted_docids_origin'] = list(porg)
item['predicted_docids_aside'] = list(paside)
d_list[i] = item
ws_second.close()
示例7: test_client_auth_timeout
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def test_client_auth_timeout(self):
with QdbServer(client_host='localhost',
client_port=0,
auth_timeout=1, # Timeout after 1 second.
tracer_server=QdbNopServer()) as server:
ws = create_connection(
'ws://localhost:%d%s' % (server.client_server.server_port,
DEFAULT_ROUTE_FMT.format(uuid='test'))
)
auth_failed_dict = fmt_err_msg('auth', 'No start event received')
disable_dict = fmt_msg('disable')
auth_failed_msg = ''
disable_msg = ''
with gevent.Timeout(2, False):
# The server should time us out in 1 second and send back these
# two messages.
auth_failed_msg = ws.recv()
disable_msg = ws.recv()
self.assertEquals(auth_failed_msg, json.dumps(auth_failed_dict))
self.assertEquals(disable_msg, json.dumps(disable_dict))
self.assertFalse('test' in server.session_store)
示例8: test_bad_auth_tracer
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def test_bad_auth_tracer(self):
"""
Tests a non-valid auth message for a tracer.
"""
with QdbServer(tracer_host='localhost',
tracer_port=0,
tracer_auth_fn=lambda _: False,
client_server=QdbNopServer()) as server:
auth_failed_dict = fmt_err_msg('auth', 'Authentication failed')
sck = gevent.socket.create_connection(
('localhost', server.tracer_server.server_port)
)
send_tracer_event(sck, 'start', {
'uuid': 'test',
'auth': 'friendzoned-again',
'local': (0, 0),
})
# We failed auth so the socket should be closed.
self.assertEqual(auth_failed_dict,
recv_tracer_event(sck))
self.assertFalse('test' in server.session_store)
示例9: test_tracer_auth_timeout
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def test_tracer_auth_timeout(self):
"""
Tests the auth timeout for new connections from the client.
"""
with QdbServer(tracer_host='localhost',
tracer_port=0,
client_server=QdbNopServer(),
auth_timeout=1) as server:
auth_failed_dict = fmt_err_msg('auth', 'No start event received')
sck = gevent.socket.create_connection(
('localhost', server.tracer_server.server_port)
)
self.assertEqual(auth_failed_dict, recv_tracer_event(sck))
self.assertFalse('test' in server.session_store)
示例10: test_client_orphan_session
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def test_client_orphan_session(self):
"""
Tests that a client makes it into the session store without a tracer
attaching if attach_timeout is set to ALLOW_ORPHANS or 0.
"""
with QdbServer(tracer_server=QdbNopServer(),
client_host='localhost',
client_port=0,
attach_timeout=ALLOW_ORPHANS) as server:
client = create_connection(
'ws://localhost:%d%s' % (server.client_server.server_port,
DEFAULT_ROUTE_FMT.format(uuid='test'))
)
send_client_event(client, 'start', '')
# yield to the session_store to let it get attached.
gyield()
self.assertIn('test', server.session_store)
示例11: test_tracer_orphan_session
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def test_tracer_orphan_session(self):
"""
Tests that a tracer makes it into the session_store without a client
attaching if attach_timeout is set to ALLOW_ORPHANS or 0.
"""
with QdbServer(client_server=QdbNopServer(),
tracer_host='localhost',
tracer_port=0,
attach_timeout=ALLOW_ORPHANS) as server:
tracer = gevent.socket.create_connection(
('localhost', server.tracer_server.server_port)
)
send_tracer_event(tracer, 'start', {
'uuid': 'test',
'auth': '',
'local': (0, 0),
})
# yield to the session_store to let it get attached.
gyield()
self.assertIn('test', server.session_store)
示例12: _connect_and_join
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def _connect_and_join(self, userid, username, mode, gameid, force_start, public_server):
logging.debug("Creating connection")
self._ws = create_connection(ENDPOINT_BOT if not public_server else ENDPOINT_PUBLIC)
self._lock = threading.RLock()
_spawn(self._start_sending_heartbeat)
self._send(["set_username", userid, username, BOT_KEY])
logging.info("Joining game")
self._gameid = None
if mode == "private":
self._gameid = gameid
if gameid is None:
raise ValueError("Gameid must be provided for private games")
self._send(["join_private", gameid, userid, BOT_KEY])
elif mode == "1v1":
self._send(["join_1v1", userid, BOT_KEY])
elif mode == "team":
self._send(["join_team", userid, BOT_KEY])
elif mode == "ffa":
self._send(["play", userid, BOT_KEY])
else:
raise ValueError("Invalid mode")
if force_start:
_spawn(self.send_forcestart)
示例13: _data_thread
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def _data_thread(self):
try:
conn = create_connection(self.addr)
except Exception:
self._controller_q.put('restart_data')
return
while self.running:
try:
data = conn.recv()
data = json.loads(data)
except WebSocketTimeoutException:
self._controller_q.put('restart_data')
return
try:
pair = data['MarketDataIncrementalRefresh']['symbol']
endpoint = 'MarketDataIncrementalRefresh'
except KeyError:
pair = data['MarketDataSnapshotFullRefresh']['symbol']
endpoint = 'MarketDataSnapshotFullRefresh'
self.data_q.put((endpoint, pair, data[endpoint], time.time()))
示例14: _trade_thread
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def _trade_thread(self):
try:
conn = create_connection(self.trader_addr)
except Exception:
log.exception('Trader Thread Error!')
self._controller_q.put('restart_trader')
return
while self.running:
try:
data = conn.recv()
except WebSocketTimeoutException:
self._controller_q.put('restart_data')
return
self.data_q.put(json.loads(data))
try:
payload = self.trade_command_q.get()
except Empty:
continue
try:
conn.send(self.sign(payload))
except (WebSocketTimeoutException, ConnectionResetError):
continue
示例15: __init__
# 需要导入模块: import websocket [as 别名]
# 或者: from websocket import create_connection [as 别名]
def __init__(self, url, connection_payload=None, **ws_options):
'''
:param url: ws:// or wss:// url to connect to
:type url: str
:param connection_payload: data to pass during initiation of the
WebSocket connection. It's passed as ``"payload"`` key of the
``connection_init`` type message.
:type connection_payload: dict
:param ws_options: options to pass to websocket.create_connection
:type ws_options: dict
'''
self.url = url
self.connection_payload = connection_payload
self.ws_options = ws_options
self.keep_alives = ['ka']