當前位置: 首頁>>代碼示例>>Python>>正文


Python websocket.create_connection方法代碼示例

本文整理匯總了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) 
開發者ID:timkpaine,項目名稱:tributary,代碼行數:23,代碼來源:input.py

示例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
        
    #---------------------------------------------------------------------- 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:20,代碼來源:vnhuobi.py

示例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 
開發者ID:OpenMined,項目名稱:PySyft,代碼行數:19,代碼來源:websocket_client.py

示例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 
開發者ID:openstack,項目名稱:networking-odl,代碼行數:23,代碼來源:websocket_client.py

示例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() 
開發者ID:eclair4151,項目名稱:AlexaControlledSamsungTV,代碼行數:26,代碼來源:remote_websocket.py

示例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() 
開發者ID:easonnie,項目名稱:combine-FEVER-NSMN,代碼行數:25,代碼來源:doc_retrieval_experiment_client.py

示例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) 
開發者ID:quantopian,項目名稱:qdb,代碼行數:27,代碼來源:test_server.py

示例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) 
開發者ID:quantopian,項目名稱:qdb,代碼行數:26,代碼來源:test_server.py

示例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) 
開發者ID:quantopian,項目名稱:qdb,代碼行數:18,代碼來源:test_server.py

示例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) 
開發者ID:quantopian,項目名稱:qdb,代碼行數:19,代碼來源:test_server.py

示例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) 
開發者ID:quantopian,項目名稱:qdb,代碼行數:22,代碼來源:test_server.py

示例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) 
開發者ID:harrischristiansen,項目名稱:generals-bot,代碼行數:27,代碼來源:generals.py

示例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())) 
開發者ID:Crypto-toolbox,項目名稱:bitex,代碼行數:23,代碼來源:hitbtc.py

示例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 
開發者ID:Crypto-toolbox,項目名稱:bitex,代碼行數:27,代碼來源:hitbtc.py

示例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'] 
開發者ID:profusion,項目名稱:sgqlc,代碼行數:19,代碼來源:websocket.py


注:本文中的websocket.create_connection方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。