• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python transport.Transport类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中transport.Transport的典型用法代码示例。如果您正苦于以下问题:Python Transport类的具体用法?Python Transport怎么用?Python Transport使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Transport类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: Mailgun

class Mailgun(object):

    def __init__(self, domain, api_key):
        self._client = Transport(domain, api_key)

    def get(self, action, *args, **kwargs):
        """
        HTTP GET method
        """
        return self._client.process(action, "get", *args, **kwargs)

    def post(self, action, *args, **kwargs):
        """
        HTTP POST method
        """
        return self._client.process(action, "post", *args, **kwargs)

    def delete(self, action, *args, **kwargs):
        """
        HTTP DELETE method
        """
        return self._client.process(action, "delete", *args, **kwargs)

    def put(self, action, *args, **kwargs):
        """
        HTTP PUT method
        """
        return self._client.process(action, "put", *args, **kwargs)
开发者ID:2014,项目名称:pymailgun,代码行数:28,代码来源:mailgun.py


示例2: main

def main():
    random.seed(0)

    d = Driver()
    t = Transport(d, isServer=False)
    services = Services(t)
    s = services.getService(TEST_ADDRESS)

    for i in itertools.count(1):
        #totalFrags = random.randrange(1, 2**16 - 1)
        totalFrags = random.randrange(1, 500)
        #totalFrags = 1000
        requestBuffer = Buffer(['a' * t.dataPerFragment() for j in range(totalFrags)])
        responseBuffer = Buffer()
        start = gettime()
        r = t.clientSend(s, requestBuffer, responseBuffer)
        r.getReply()
        elapsedNs = gettime() - start
        resp = responseBuffer.getRange(0, responseBuffer.getTotalLength())
        req = requestBuffer.getRange(0, requestBuffer.getTotalLength())
        assert len(req) == len(resp), (len(req), len(resp), req[:10], resp[:10],
                                       req[-10:], resp[-10:])
        assert req == resp, (req, resp)
        print
        print "Message %d with %d frags OK in %dms" % (i, totalFrags,
                                                       elapsedNs / 1000000)
        d.stat()
开发者ID:609467829,项目名称:RAMCloud,代码行数:27,代码来源:client.py


示例3: __init__

    def __init__(self, jobname, compute_nodes, replicas): #changed on 12/1/14
        # jobname: identifies current asyncRE job
        # compute_nodes: list of names of nodes in the pool
        # nreplicas: number of replicas, 0 ... nreplicas-1
        Transport.__init__(self) #WFF - 2/18/15
        self.logger = logging.getLogger("async_re.ssh_transport") #WFF - 3/2/15

        # names of compute nodes (slots)
        self.compute_nodes = compute_nodes #changed on 12/1/14
        self.nprocs = len(self.compute_nodes)
        #self.openmm_platform = None
                        
        # node status = None if idle
        # Otherwise a structure containing:
        #    replica number being executed
        #    process id
        #    process name
        #    ...
        self.node_status = [ None for k in range(self.nprocs)]
	#self.openmm_platform = None
	

        # contains the nodeid of the node running a replica
        # None = no information about where the replica is running
        self.replica_to_job = [ None for k in replicas ]

        # implements a queue of jobs from which to draw the next job
        # to launch
        self.jobqueue = Queue.Queue()
开发者ID:baofzhang,项目名称:async_re-openmm,代码行数:29,代码来源:ssh_transport.py


示例4: TestTransport

class TestTransport(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setUpClass')

    def setUp(self):
        #print('setUp')
        self.transport = Transport(speed=120)

    def tearDown(self):
        #print('tearDown')
        del self.transport

    def test_drive(self):

        # assert True, True

        self.transport.drive(10)

        self.assertEqual(self.transport.pos, 1200)

    def test_drive2(self):
        self.transport.drive(10)

        self.assertEqual(self.transport.pos, 1200)

    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")
开发者ID:compasrumobile,项目名称:curs_2016,代码行数:30,代码来源:test_transport.py


示例5: __init__

    def __init__(self, **kwargs):
        """

        :param host:
        :param port:
        :param timeout:
        :param connect:
        :return:
        """
        port = get_kwarg('port', kwargs, 7147)
        timeout = get_kwarg('timeout', kwargs, 10)
        Transport.__init__(self, **kwargs)

        # Create instance of self.logger
        try:
            self.logger = kwargs['logger']
        except KeyError:
            self.logger = logging.getLogger(__name__)

        new_connection_msg = '*** NEW CONNECTION MADE TO {} ***'.format(self.host)
        self.logger.info(new_connection_msg)

        katcp.CallbackClient.__init__(
            self, self.host, port, tb_limit=20,
            timeout=timeout, logger=self.logger, auto_reconnect=True)
        self.system_info = {}
        self.unhandled_inform_handler = None
        self._timeout = timeout
        self.connect()
        self.logger.info('%s: port(%s) created and connected.' % (self.host, port))
开发者ID:ska-sa,项目名称:casperfpga,代码行数:30,代码来源:transport_katcp.py


示例6: main

def main():
    d = Driver(TEST_ADDRESS)
    t = Transport(d, isServer=True)
    while True:
        r = t.serverRecv()
        r.replyPayload.extend(r.recvPayload)
        r.sendReply()
        d.stat()
开发者ID:609467829,项目名称:RAMCloud,代码行数:8,代码来源:server.py


示例7: __init__

 def __init__(self, debug=False, verbose=False):
     self.client.login()
     if verbose:
         self.log.basicConfig(level=self.log.INFO)
     if debug:
         self.log.basicConfig(level=self.log.DEBUG)
     Transport.__init__(self, self.client, self.log)
     NetworkServices.__init__(self, self.client, self.log)
     ControlServices.__init__(self, self.client, self.log)
开发者ID:thecantero,项目名称:nvpnsxapi,代码行数:9,代码来源:nvp_api.py


示例8: TestTransport2

class TestTransport2(unittest.TestCase):

    def setUp(self):
        self.transport = Transport(speed=120)

    def test_drive(self):
        self.transport.drive(10)

        self.assertEqual(self.transport.pos, 1200)
开发者ID:compasrumobile,项目名称:curs_2016,代码行数:9,代码来源:test_transport.py


示例9: __init__

class Client:

    def __init__(self):
        self.transport = None
        self.torrents = {}
        self.torrent_keys = ['queue', 'name', 'total_size',
                'state', 'progress', 'num_seeds', 'files',
                'download_payload_rate', 'upload_payload_rate']
        self.session_keys = ['download_rate', 'payload_download_rate',
                'upload_rate', 'payload_upload_rate']

    def connect(self, host="127.0.0.1", port=58846, username="", password=""):
        self.transport = Transport(host, port)

        try:
            r = self.transport.login(username, password)
        except Exception, e:
            print "login failed", e
            self.transport = None
            return False

        print "login infor is r", r
        print "Protocol version", self.transport.daemon_info()

        for event, handler in [
                ('TorrentStateChangedEvent', self._on_torrent_state_changed),
                ('TorrentRemovedEvent', self._on_torrent_removed),
                ('TorrentAddedEvent', self._on_torrent_added)]:

            if not self.transport.register_event_handler(event, handler):
                print "Failed to register handler", event, handler

        self.torrents = self.transport.torrent_status(None, self.torrent_keys)
        return True
开发者ID:jamielennox,项目名称:xbmc-deluge,代码行数:34,代码来源:client.py


示例10: __init__

class Client:
  def __init__(self, user):
    self.user = user
    self.ip = str(54) + '.' + str(random.randrange(0, 255)) + '.' + str(random.randrange(0, 255)) + '.' + str(random.randrange(0, 255))
    self.connections = []
    self.routerBuffer = []
    self.inbox = {}
    self.transportLayer = Transport(self)
    self.applicationLayer = Application(self)

  # Adds a link between this client and another
  def addConnection(self, client):
    if client == self:
      return
    if client.ip in self.connections:
      return
    self.connections.append(client.ip)

  # Sends a message (tells the application layer to make a packet)
  def sendMessage(self, source, destination, message , time):
    applicationPacket = self.applicationLayer.generatePacket(time, source, destination, message)
    tcpPackets = self.transportLayer.process(applicationPacket, time)

  def __repr__(self):
    return self.ip

  def __str__(self):
    return self.ip + ' - ' + str(self.connections) + " => Router Buffer: " + str(self.routerBuffer) + "  Inbox: " + str(self.inbox)
开发者ID:nburfield,项目名称:CPE-400-Networking-Project,代码行数:28,代码来源:client.py


示例11: connect

    def connect(self, host="127.0.0.1", port=58846, username="", password=""):
        self.transport = Transport(host, port)

        try:
            r = self.transport.login(username, password)
        except Exception, e:
            print "login failed", e
            self.transport = None
            return False
开发者ID:jamielennox,项目名称:xbmc-deluge,代码行数:9,代码来源:client.py


示例12: __init__

 def __init__(self, intf):
     self._intf = intf
     self._transport = Transport()
     self._id = None
     self._version = None
     self._polling = False
     self._connected = False
     self._ndefMessagePresent = False
     self._ndefRecords = None
     self._ndefRead = False
开发者ID:thejarle,项目名称:micronfcboard-python,代码行数:10,代码来源:board.py


示例13: Main

class Main(object):
    def __init__(self):
        self.monitor = None

        try:
            # instanciates the config
            self.config = Config()

            # exists baboon when receiving a sigint signal
            signal.signal(signal.SIGINT, self.sigint_handler)

            # Initialize the scm class to use
            scm_classes = Diffman.__subclasses__()
            for cls in scm_classes:
                tmp_inst = cls()
                if tmp_inst.scm_name == self.config.scm:
                    self.diffman = tmp_inst

            # TODO verify self.diffman

            self.mediator = Mediator(self.diffman)

            self.transport = Transport(self.mediator)
            self.transport.open()

            self.monitor = Monitor(self.transport, self.diffman)
            self.monitor.watch()

            # TODO this won't work on windows...
            signal.pause()

        except BaboonException, err:
            sys.stderr.write("%s\n" % err)
            # Try to close the transport properly. If the transport is
            # not correctly started, the close() method has no effect.
            self.transport.close()

            # Same thing for the monitor
            if self.monitor:
                self.monitor.close()

            # Exits with a fail return code
            sys.exit(1)
开发者ID:raphdg,项目名称:baboon,代码行数:43,代码来源:main.py


示例14: __init__

    def __init__(self, jobname, keywords, nreplicas, files_to_stage):
        # jobname: identifies current asyncRE job
        # files_to_stage: permanent files to stage into BOINC download directory (main struct file, datafiles, etc.)
        Transport.__init__(self)
        self.logger = logging.getLogger("async_re.boinc_transport")

        self.jobname = jobname

        # variables required for boinc-based transport
        if keywords.get('BOINC_PROJECTDIR') is None:
            self._exit("BOINC transport requires a BOINC_PROJECTDIR")
        self.project_dir = keywords.get('BOINC_PROJECTDIR')
        if not os.path.isdir(self.project_dir):
            self.logger.critical("Unable to located BOINC project directory: %s",
                                 self.project_dir)
            sys.exit(1)

        #sets up a mapping between replicas running and work unit ids
        self.replica_to_wuid = [ None for k in range(nreplicas)]

        #sets up lookup table for replica done status
        self.replica_status = dict()

        #set connection with mysql boinc server database
        if keywords.get('BOINC_DATABASE') is None:
            self.logger.critical("BOINC transport requires a BOINC_DATABASE")
            sys.exit(1)
        if keywords.get('BOINC_DATABASE_USER') is None:
            self.logger.critical("BOINC transport requires a BOINC_DATABASE_USER")
            sys.exit(1)
        if keywords.get('BOINC_DATABASE_PASSWORD') is None:
            self.logger.critical("BOINC transport requires a BOINC_DATABASE_PASSWORD")
            sys.exit(1)
        self.db_name = keywords.get('BOINC_DATABASE')
        self.db_user = keywords.get('BOINC_DATABASE_USER')
        self.db_pwd = keywords.get('BOINC_DATABASE_PASSWORD')

        # stage files
        if files_to_stage is not None:
            for file in files_to_stage:
                filepath = os.getcwd() + "/" + file
                self._stage_file(filepath,file)
开发者ID:baofzhang,项目名称:async_re-openmm,代码行数:42,代码来源:boinc_transport.py


示例15: Player

class Player(object):

    auth_timeout = 5

    def __init__(self, socket, address):
	self.transport = Transport(socket, address)
	self.host = address[0]
	self.port = address[1]
	self.health = 100

    def close(self):
	self.transport.send(Message.exit().pack())
	self.transport.close()

    def auth(self):
	recv = None
	with Timeout(Player.auth_timeout, PlayerError("Authentication timed out")):
	    try:
		msg = self.transport.receive()
	    except PlayerError as e:
		print("error on receive")
		print(e)
		return False

	try:
	    msg = Message.parse(msg)
	except MessageError:
	    print("bad message")
	    return False
	if msg.type == "nick":
	    self.name = msg.payload
	    self.transport.send(Message.auth_success().pack())
	    return True
	return False

    def listen(self):
	return self.transport.receive()

    def send(self, msg):
	self.transport.send(msg)
开发者ID:jhuang314,项目名称:pyaudio,代码行数:40,代码来源:player.py


示例16: __init__

    def __init__(self, **kwargs):
        """
        Initialized Tapcp FPGA object
        :param host: IP Address of the targeted Board
        :return: none
        """
        try:
            import tftpy
            global TFTPY
            TFTPY = tftpy
        except ImportError:
            raise ImportError('You need to install tftpy to use TapcpTransport')
        Transport.__init__(self, **kwargs)
        set_log_level(logging.ERROR)
        self.t = tftpy.TftpClient(kwargs['host'], 69)
        try:
            self.logger = kwargs['logger']
        except KeyError:
            self.logger = logging.getLogger(__name__)

        new_connection_msg = '*** NEW CONNECTION MADE TO {} ***'.format(self.host)
        self.logger.info(new_connection_msg)
        self.timeout = kwargs.get('timeout', 3)
开发者ID:ska-sa,项目名称:casperfpga,代码行数:23,代码来源:transport_tapcp.py


示例17: __init__

    def __init__(self, **params):
        self.params = params
        self.transport = Transport()
        self.reader = DelimitedReader("\r\n")
        self.reader.add_callback(self.new_line)
        self._services = []
        for t in type(self).COMMON_SERVICES:
            self.add_service(t())
        for i in self.services():
            self.add_service(i)
        self.lock_many = threading.Lock()
        self.lock_single = threading.Lock()

        self.common_state = {"irc": self}
开发者ID:Zekka,项目名称:bakten,代码行数:14,代码来源:client.py


示例18: connect

    def connect(self):
        self.t = Transport(self.host, self.port, timeout=None, verbose=False)
        if not self.upgrade_connection():
            raise ServerError('Unable to upgrade connection')
        self.log("Connected to {0}:{1}.".format(self.host, self.port))

        response = self.send_init_request()
        if response.responseCode != 200:
            error_text = 'Wrong response from server, status_code={0}'.format(
                response.responseCode)
            if response.HasField("message"):
                error_text += ', message is "{0}"'.format(response.message)
            raise ServerError(error_text)

        self.session_id = response.sessionId
        self.log("session_id={0}".format(self.session_id))

        return self.session_id
开发者ID:hoverjet,项目名称:speechkitcloud,代码行数:18,代码来源:client.py


示例19: __init__

 def __init__(self, intf):
     self._intf = intf
     self._transport = Transport()
     self._id = None
     self._version = None
     self._polling = False
     self._connected = False
     self._type2 = False
     self._type4 = False
     self._p2p = False
     self._initiator = False
     self._ndefPresent = False
     self._ndefRecords = None
     self._ndefRead = False
     self._ndefReadable = False
     self._ndefWriteable = False
     self._ndefBusy = False
     self._ndefSuccess = False
开发者ID:oliviermartin,项目名称:micronfcboard-python,代码行数:18,代码来源:board.py


示例20: __init__

 def __init__(self, mode, applications, own_ip):
   Transport.__init__(self, mode, applications, own_ip)
   self.connection = Connection
   self.name = 'UDP'
   self.socktype = SOCK_DGRAM
   self.server = Udpserver
开发者ID:siemens,项目名称:sparring,代码行数:6,代码来源:udp.py



注:本文中的transport.Transport类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python db.create_engine函数代码示例发布时间:2022-05-27
下一篇:
Python transmitter.Transmitter类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap