本文整理匯總了Python中transport.Transport類的典型用法代碼示例。如果您正苦於以下問題:Python Transport類的具體用法?Python Transport怎麽用?Python Transport使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Transport類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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)
示例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()
示例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()
示例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")
示例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))
示例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()
示例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)
示例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)
示例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
示例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)
示例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
示例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
示例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)
示例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)
示例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)