python类create_connection()的实例源码

connector.py 文件源码 项目:catalearn 作者: Catalearn 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def stream_output(gpu_ip, ws_port, job_hash):
    # connect to the websocket for this job
    url = 'ws://%s:%s' % (gpu_ip, ws_port)
    ws = create_connection(url)
    # send over the job hash to start the job
    ws.send(job_hash)
    # print all the outputs of the script to the screen
    # try:
    while True:
        msg = ws.recv()
        msgJson = json.loads(msg)
        if 'end' in msgJson:
            break
        else:
            print(msgJson['message'], end='')
    ws.close()
    return msgJson['hasResult']

    # if the user interrupts the job, decide whether or not to stop
    # except KeyboardInterrupt:
    #     # propagate the exception for the layer above to handle
    #     raise JobInterruptedException()
generals.py 文件源码 项目:generals-bot 作者: harrischristiansen 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
panono.py 文件源码 项目:panonoctl 作者: florianl 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def connect(self):
        """

        Opens a connection

        """
        ws = None
        # Let us discover, where we need to connect to
        if self.ip == None or self.port == None:
            (ws, self.usn, self.apiV, self.srv) = ssdp.discover(None)
        else:
            ws = "ws://%s" % self.ip
            if not self.port is None:
                ws = "{}:{}".format(ws, self.port)
            if not self.path is None:
                ws = "{}/{}".format(ws, self.path)
        if ws == None:
            return False
        self.ws = websocket.create_connection(ws)
        return True
hitbtc.py 文件源码 项目:bitex 作者: nlsdfnbch 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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()))
zynthian_engine_modui.py 文件源码 项目:zynthian-ui 作者: zynthian 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def start_websocket(self):
        logging.info("Connecting to MOD-UI websocket...")
        i=0
        while i<100:
            try:
                self.websocket = websocket.create_connection(self.websocket_url)
                break
            except:
                i=i+1
                sleep(0.1)
        if i<100:
            self.ws_thread=Thread(target=self.task_websocket, args=())
            self.ws_thread.daemon = True # thread dies with the program
            self.ws_thread.start()
            return True
        else:
            return False
logs.py 文件源码 项目:siphon-cli 作者: getsiphon 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def stream_logs():
    conf = Config()
    # Request the correct streamer URL from siphon-web
    auth = Auth()
    siphon = Siphon(auth.auth_token)

    # Track
    mixpanel_event(MIXPANEL_EVENT_LOGS, properties={'app_id': conf.app_id})

    streamer_url = siphon.get_streamer_url(conf.app_id, 'log_reader')

    puts(colored.yellow('Connecting...'))
    ws = websocket.create_connection(streamer_url)
    puts(colored.green('Streaming logs and errors... (ctrl-c to stop)\n'))
    try:
        for line in ws:
            print(line)
    except KeyboardInterrupt:
        puts(colored.yellow('\nClosing the connection.'))
        ws.close()
ok.py 文件源码 项目:treadmill 作者: Morgan-Stanley 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def check_ws_api():
    """Check websocket API."""
    success = True
    try:
        for api in context.GLOBAL.ws_api(None):
            try:
                ws_client.create_connection(api)
                _LOGGER.debug('%s - ok.', api)
            except socket.error:
                _LOGGER.error('%s - failed.', api)
                success = False
    except context.ContextError as err:
        _LOGGER.error('Unable to resolve websocket api: %r', str(err))
        success = False

    return success
integration_tests.py 文件源码 项目:django-channels-router 作者: Monadical-SAS 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def connect_socket(url, timeout=TIMEOUT, **kwargs):
    """set up a websocket and return the socket connection object"""

    signal.signal(
        signal.SIGALRM, 
        lambda s, f: timeout_handler(s, f, f'connecting ({timeout}s)')
    )
    signal.alarm(timeout)
    try:
        sock = create_connection(url, **kwargs)
        signal.alarm(0)
        return sock
    except Exception:
        signal.alarm(0)
        print(f'[X] Failed to connect, is runserver running on {url}?')
        raise
    except Exception:
        signal.alarm(0)
        raise
integration_tests.py 文件源码 项目:django-channels-router 作者: Monadical-SAS 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def run(self):
        signal.alarm(0)
        self.ws = create_connection(self.url, **self.socket_options)
        self.ws.send(json.dumps(self.get_message()))
        resp = self.ws.recv()
        resp = self.ws.recv()
        assert resp and self.check_response(json.loads(resp)), \
                'Failed to get expected response from backend.'
        self.started.set()
        self.should_start.wait()
        while self.keep_running:
            try:
                msg = self.get_message()
                self.ws.send(json.dumps(msg))
                resp = json.loads(self.ws.recv())
                if self.verbose:
                    print('sent:', msg[ROUTING_KEY], 
                        '  recv:', resp[ROUTING_KEY])
                assert resp and self.check_response(resp), \
                        'Failed to get expected response from backend.'
                self.round_trips += 1
            except Exception:
                if self.keep_running:
                    raise
library.py 文件源码 项目:chrome_remote_interface_python 作者: wasiher 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __init__(self, host, port, tabs=None, tab_id=None):
        super().__init__(host, port)
        self._host = host
        self._port = port
        if tab_id is None:
            tab_info = json.loads(call_method(self._host, self._port, 'new'))
            self._id = tab_info['id']
            self._ws_url = tab_info['webSocketDebuggerUrl']
        else:
            try:
                tab_info = None
                for current_tab_info in json.loads(call_method(self._host, self._port, 'list')):
                    if current_tab_info['id'] == tab_id:
                        tab_info = current_tab_info
                if tab_info is None:
                    raise ValueError('Tab {0} not found'.format(tab_id))
                self._id = tab_info['id']
                self._ws_url = tab_info['webSocketDebuggerUrl']
            except:
                self._id = tab_id
                self._ws_url = 'ws://{0}:{1}/devtools/page/{2}'.format(self._host, self._port, tab_id)
        self._soc = websocket.create_connection(self._ws_url)
        self._i = 0
        self._tabs = tabs
sc_process.py 文件源码 项目:pysc2 作者: deepmind 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _connect(self, port):
    """Connect to the websocket, retrying as needed. Returns the socket."""
    was_running = False
    for i in range(120):
      is_running = self.running
      was_running = was_running or is_running
      if (i >= 30 or was_running) and not is_running:
        logging.warning(
            "SC2 isn't running, so bailing early on the websocket connection.")
        break
      logging.info("Connection attempt %s (running: %s)", i, is_running)
      time.sleep(1)
      try:
        return websocket.create_connection("ws://127.0.0.1:%s/sc2api" % port,
                                           timeout=2 * 60)  # 2 minutes
      except socket.error:
        pass  # SC2 hasn't started listening yet.
      except websocket.WebSocketException as err:
        if "Handshake Status 404" in str(err):
          pass  # SC2 is listening, but hasn't set up the /sc2api endpoint yet.
        else:
          raise
    sys.exit("Failed to create the socket.")
wee_slack.py 文件源码 项目:dotfiles 作者: jethrokuan 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def connect(self):
        if not self.connected and not self.connecting:
            self.connecting = True
            if self.ws_url:
                try:
                    ws = create_connection(self.ws_url, sslopt=sslopt_ca_certs)
                    self.hook = w.hook_fd(ws.sock._sock.fileno(), 1, 0, 0, "receive_ws_callback", self.get_team_hash())
                    ws.sock.setblocking(0)
                    self.ws = ws
                    # self.attach_websocket(ws)
                    self.set_connected()
                    self.connecting = False
                except Exception as e:
                    dbg("websocket connection error: {}".format(e))
                    self.connecting = False
                    return False
            else:
                # The fast reconnect failed, so start over-ish
                for chan in self.channels:
                    self.channels[chan].got_history = False
                s = SlackRequest(self.token, 'rtm.start', {}, retries=999)
                self.eventrouter.receive(s)
                self.connecting = False
                # del self.eventrouter.teams[self.get_team_hash()]
            self.set_reconnect_url(None)
gateway_socket.py 文件源码 项目:dissonance 作者: jhgg 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _ws_loop(self, gateway):
        self._status = Status.CONNECTING
        self._ws = create_connection(gateway)
        self._seq = 0

        self._send(PacketBuilder.identify(self._client.api_client.token))
        initial_packet = self._recv()
        self._on_initial_packet(initial_packet)
        self._on_packet(initial_packet)

        try:
            while True:
                packet = self._recv()
                self._on_packet(packet)

        finally:
            if self._heartbeat_greenlet:
                self._heartbeat_greenlet.kill()

            self._ws_greenlet = None
connection.py 文件源码 项目:smileybot 作者: sillylyn 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def connect(self, room):
        """
        connect(room) -> Bool

        Connect to the given room. Cannot send messages without first
        connecting.
        """

        self.room = room

        url = "wss://%s/room/%s/ws" % (self.site, self.room)

        try:
            self.socket = websocket.create_connection(url, enable_multithread=True, timeout=40)
        except (websocket.WebSocketException, IOError):
            self.socket = None
            return False

        return True
browser.py 文件源码 项目:DataBot 作者: Mego 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def start(self):
        last_event_time = self.browser.rooms[self.room_id]['eventtime']

        ws_auth_data = self.browser.post_fkeyed(
            'ws-auth',
            {'roomid': self.room_id}
        ).json()
        wsurl = ws_auth_data['url'] + '?l=%s' % (last_event_time,)
        self.logger.debug('wsurl == %r', wsurl)

        self.ws = websocket.create_connection(
            wsurl, origin=self.browser.chat_root)

        self.thread = threading.Thread(target=self._runner)
        self.thread.setDaemon(True)
        self.thread.start()
learning.py 文件源码 项目:5c-hacks-s16 作者: nhurwitz 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def play_net(model, params):
    ws = create_connection("ws://localhost:8000/ws")
    welcomeJson = ws.recv()
    welcome = json.loads(welcomeJson)
    clientId = welcome['snakeID']

    while True:
      state = ws.recv()
      parsed = json.loads(state)

      if parsed['eventType'] != 'World':
        continue

      qval = model.predict(world_json_to_array(parsed['world'], clientId), batch_size=1)
      action = (np.argmax(qval))  # best
      ws.send(json.dumps({"actionType": "Direction", "snakeID": clientId, "direction": intToDirection(action)}))
timeseries.py 文件源码 项目:predixpy 作者: PredixDev 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _create_connection(self):
        """
        Create a new websocket connection with proper headers.
        """
        logging.debug("Initializing new websocket connection.")
        headers = {
            'Authorization': self.service._get_bearer_token(),
            'Predix-Zone-Id': self.ingest_zone_id,
            'Content-Type': 'application/json',
        }
        url = self.ingest_uri

        logging.debug("URL=" + str(url))
        logging.debug("HEADERS=" + str(headers))

        # Should consider connection pooling and longer timeouts
        return websocket.create_connection(url, header=headers)
nb_entity.py 文件源码 项目:enterprise_gateway 作者: jupyter-incubator 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_cells(self, nb_test_case):
        # Execute all code cells in a notebook code entity, get the response message in JSON format,
        # and return all code cells parsed by messages in a list.
        errors = 0
        ws_url = nb_test_case.elyra_client.get_ws_kernel_endpoint(self.kernel_id)
        ws = websocket.create_connection(url=ws_url, timeout=itest_cell_timeout)
        print("Connection created for web socket {}".format(ws_url))
        try:
            code_cell_count = 1
            for code_cell in self.code_cell_list:
                if code_cell.is_executed():
                    errors = errors + NBCodeEntity.test_cell(nb_test_case, ws, code_cell, code_cell_count)
                code_cell_count = code_cell_count+1
        finally:
            ws.close()
        return errors
gpmdp.py 文件源码 项目:homeassistant 作者: NAStools 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, name, url, code):
        """Initialize the media player."""
        from websocket import create_connection
        self._connection = create_connection
        self._url = url
        self._authorization_code = code
        self._name = name
        self._status = STATE_OFF
        self._ws = None
        self._title = None
        self._artist = None
        self._albumart = None
        self._seek_position = None
        self._duration = None
        self._volume = None
        self._request_id = 0
        self.update()
__init__.py 文件源码 项目:ChromeHeadlessInterface 作者: wilson9x1 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _open_new_tab(self):
        url = ChromeAPI.OPEN_NEW_TAB_URL.format(self._host, self._port)
        try:
            response = requests.get(url)
        except Exception as e:
            print("Error while access {0}, please check chrome browser.".format(url))
            print("Details error: {0}".format(e))
            return False
        response = response.json()
        tab_id = response.get("id")
        if not tab_id:
            return False
        ws_url = response.get("webSocketDebuggerUrl")
        if not ws_url:
            return False

        ws_instance = websocket.create_connection(ws_url, timeout=self._timeout)
        if not ws_instance:
            return False

        self._tab = {
            "tab_id": tab_id,
            "ws_url": ws_url,
            "ws_instance": ws_instance
        }
        return self._tab
chrome_headless.py 文件源码 项目:ChromeHeadlessInterface 作者: wilson9x1 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, url, ip="127.0.0.1", port="9222", cookie="", post="", auth=""):
        """
        ???
        :param url: ??url
        :param ip: ChromeHeadless?server ip
        :param port: ChromeHeadless?server ??
        :param cookie: ??cookie
        :param post:  ??post Chrome?api???
        :param auth:  ?? authorization
        """
        self.url = url
        self.cookie = cookie
        self.post = post
        self.auth = auth
        self.ip = ip
        self.port = port
        self.tab_id = ""
        self.ws_url = ""
        self.hook_urls = []
        self.error = ""
        self.soc = None
        self.javascript_dialog_events = []
        chrome_web = "http://%s:%s/json/new" % (ip, port)
        try:
            response = requests.get(chrome_web)
            self.ws_url = response.json().get("webSocketDebuggerUrl")
            self.tab_id = response.json().get("id")
            self.soc = websocket.create_connection(self.ws_url)
            # print(self.ws_url, self.tab_id)
        except Exception, e:
            # print "ERROR:%s" % e
            self.error = str(e)
chrome_headless.py 文件源码 项目:ChromeHeadlessInterface 作者: wilson9x1 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def send_msg(self, id, method, params):
        """
        ?ChromeHeadless?server ?????
        :param id:
        :param method:
        :param params:
        :return:
        """
        # soc = websocket.create_connection(ws_url)
        navcom = json.dumps({
            "id": id,
            "method": method,
            "params": params
        })
        self.soc.send(navcom)
jpegbot.py 文件源码 项目:NeedsMoreJPEGBot 作者: Arwic 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def auth_rockets():
    global rockets_ws
    print('Attempting to connect to rockets...')
    rockets_ws = create_connection("ws://rockets.cc:3210")
    rockets_ws.send(rockets_subscription)
    print('Success!')


# downloads an image from imgur
# returns: image path
wee_discord.py 文件源码 项目:wee-discord 作者: BlitzKraft 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def create_slack_websocket(self, data):
        web_socket_url = data['url']
        try:
            self.ws = create_connection(web_socket_url, sslopt=sslopt_ca_certs)
            self.ws_hook = w.hook_fd(self.ws.sock._sock.fileno(), 1, 0, 0, "slack_websocket_cb", self.identifier)
            self.ws.sock.setblocking(0)
            return True
        except Exception as e:
            print("websocket connection error: {}".format(e))
            return False
generals.py 文件源码 项目:generalscnn 作者: zxqfl 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self, userid, username, mode="1v1", gameid=None,
                 force_start=True, region=None):
        logging.debug("Creating connection")
        self._ws = create_connection(_ENDPOINT)
        self._lock = threading.RLock()

        logging.debug("Starting heartbeat thread")
        _spawn(self._start_sending_heartbeat)

        logging.debug("Joining game")
        self._send(["set_username", userid, username])

        if mode == "private":
            if gameid is None:
                raise ValueError("Gameid must be provided for private games")
            self._send(["join_private", gameid, userid])

        elif mode == "1v1":
            self._send(["join_1v1", userid])

        elif mode == "team":
            if gameid is None:
                raise ValueError("Gameid must be provided for team games")
            self._send(["join_team", gameid, userid])

        elif mode == "ffa":
            self._send(["play", userid])

        else:
            raise ValueError("Invalid mode")

        self._send(["set_force_start", gameid, force_start])

        self._seen_update = False
        self._move_id = 1
        self._start_data = {}
        self._stars = []
        self._map = []
        self._cities = []
proxy.py 文件源码 项目:Cloudroid 作者: cyberdb 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_remote_topic_type(topic_name, url):
    while True:
        try:
            ws = websocket.create_connection(url)
            break
        except Exception, e:
            rospy.loginfo('Create connection to Rosbridge server %s failed, retrying. Reason: %s', url, str(e))

        time.sleep(2)        

    try:
        # get topic type
        ws.send(json.dumps({
            'op': 'call_service',
            'service': '/rosapi/topic_type',
            'args': [topic_name]
        }))
        x = json.loads(ws.recv())

        assert x['service'] == '/rosapi/topic_type'

        ws.close()

        if x['result']:
            return x['values']['type']    
        else:
            return ""   
    except Exception, e:
        rospy.logerr('Get the type of topic %s from Rosbridge server %s failed. Reason: %s', topic_name, url, str(e))
        ws.close()
        return ""
proxy.py 文件源码 项目:Cloudroid 作者: cyberdb 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def get_remote_service_info(service_name, url):
    while True:
        try:
            ws = websocket.create_connection(url)
            break
        except Exception, e:
            rospy.loginfo('Create connection to Rosbridge server %s failed, retrying. Reason: %s', url, str(e))

        time.sleep(2)        

    try:
        # get topic type
        ws.send(json.dumps({
            'op': 'call_service',
            'service': '/rosapi/service_type',
            'args': [service_name]
        }))
        x = json.loads(ws.recv())
        assert x['service'] == '/rosapi/service_type'
        ws.close()

        if x['result']:
            return x['values']['type'] 
        else:
            return ""
    except Exception, e:
        rospy.logerr('Get the type of service %s from Rosbridge server %s failed. Reason: %s', service_name, url, str(e))
        ws.close()
        return ""
generals.py 文件源码 项目:generals_a3c 作者: yilundu 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, userid, username, mode="1v1", gameid=None,
                 force_start=True, region=None):
        logging.debug("Creating connection")
        self._ws = create_connection(_ENDPOINT)
        self._lock = threading.RLock()

        logging.debug("Starting heartbeat thread")
        _spawn(self._start_sending_heartbeat)

        logging.debug("Joining game")
        self._send(["set_username", userid, username])

        if mode == "private":
            if gameid is None:
                raise ValueError("Gameid must be provided for private games")
            self._send(["join_private", gameid, userid])

        elif mode == "1v1":
            self._send(["join_1v1", userid])

        elif mode == "team":
            if gameid is None:
                raise ValueError("Gameid must be provided for team games")
            self._send(["join_team", gameid, userid])

        elif mode == "ffa":
            self._send(["play", userid])

        else:
            raise ValueError("Invalid mode")

        self._send(["set_force_start", gameid, force_start])

        self._seen_update = False
        self._move_id = 1
        self._start_data = {}
        self._stars = []
        self._map = []
        self._cities = []
SongRequest.py 文件源码 项目:kritzbot-legacy 作者: kritzware 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def execute_command(self, command):
        from modules.bot import bot_msg

        print("Link:", self.request)
        youtube_id = self.get_link_id(self.request)
        print("ID:", youtube_id)

        # if(database.db_add_song_request(youtube_id, self.user)):
        response = self.get_song_request(youtube_id)
        bot_msg(response)

        # send to db:
        # user, id, timestamp, position (get this on insert)

        # test stuff
        # ws = create_connection("ws://localhost:3001", subprotocols=["echo-protocol"])
        # print("Sending 'Hello world!'")
        # ws.send("Hello, world!")
websocketclient.py 文件源码 项目:zun 作者: openstack 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def connect(self):
        url = self.host_url
        try:
            self.ws = websocket.create_connection(url,
                                                  skip_utf8_validation=True)
        except socket.error as e:
            raise exception.ConnectionFailed(e)
        except websocket.WebSocketConnectionClosedException as e:
            raise exception.ConnectionFailed(e)
        except websocket.WebSocketBadStatusException as e:
            raise exception.ConnectionFailed(e)


问题


面经


文章

微信
公众号

扫码关注公众号