本文整理汇总了Python中haigha.connection.Connection类的典型用法代码示例。如果您正苦于以下问题:Python Connection类的具体用法?Python Connection怎么用?Python Connection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Connection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, **kwargs):
properties = {
"host": "localhost",
"port": 5672,
"user": "guest",
"password": "guest",
"vhost": "/",
"heartbeat": None,
"debug": False
}
self.kwargs = kwargs
for key, value in kwargs.iteritems():
if properties.has_key(key):
properties[key] = value
# Connection can be shared between multiple clients/workers
conn = self.kwargs.get("conn", None)
if conn is None:
conn = Connection(**properties)
self._conn = conn
self.channel = conn.channel()
示例2: FibonacciRpcClient
class FibonacciRpcClient(object):
def __init__(self):
self.connection = Connection(host='localhost',
heartbeat=None, debug=True)
self.channel = self.connection.channel()
result = self.channel.queue.declare(exclusive=True)
self.callback_queue = result[0]
print("callback_queue:", self.callback_queue)
self.channel.basic.consume(self.callback_queue,
self.on_response, no_ack=True)
def on_response(self, msg):
if msg.properties["correlation_id"] == self.corr_id:
self.response = msg.body
def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4())
msg = Message(str(n), reply_to=self.callback_queue,
correlation_id=self.corr_id)
self.channel.basic.publish(msg, '', 'rpc_queue')
while self.response is None:
self.connection.read_frames()
return int(self.response)
示例3: AsyncClient
class AsyncClient(object):
__metaclass__ = ClientMeta
def start(self, **kwargs):
self.connection = Connection(**kwargs)
self.channel = self.connection.channel()
self.loop = TaskLoop()
self.insert_task(self.read_frames, interval=0.01)
self.insert_task(self.__run)
self.loop.start()
def __run(self):
for declaration in itertools.chain(self._exchanges, self._queues, self._consumers):
declaration.client = weakref.ref(self)
declaration.declare()
# start 'auto' tasks
for name, attr in self.__class__.__dict__.iteritems():
if isinstance(attr, Task) and attr.auto:
getattr(self, name)()
for task, args, kwargs in self._tasks:
print 'scheduling %s from _tasks' % task
self.insert_task(task, *args, **kwargs)
# if there's a run function which isn't already a task, queue it
class_run = getattr(self.__class__, 'run', None)
self_run = getattr(self, 'run', None)
if callable(self_run) and not isinstance(class_run, Task):
self.run()
self.stop()
def stop(self):
self.connection.close()
def insert_task(self, task, *args, **kwargs):
loop = getattr(self, 'loop', None)
if isinstance(loop, TaskLoop):
loop.insert_task(task, *args, **kwargs)
else:
self._tasks.append((task, args, kwargs))
def read_frames(self):
if self.connection.close_info:
self.loop.stop()
else:
self.connection.read_frames()
@task
def basic_qos(self, **kwargs):
self.channel.basic.qos(**kwargs)
示例4: test_init_without_keyword_args
def test_init_without_keyword_args(self):
conn = Connection.__new__(Connection)
strategy = mock()
transport = mock()
mock(connection, 'ConnectionChannel')
expect(connection.ConnectionChannel).args(conn, 0, {}).returns('connection_channel')
expect(socket_transport.SocketTransport).args(conn).returns(transport)
expect(conn.connect).args('localhost', 5672)
conn.__init__()
assert_false(conn._debug)
assert_equal(logging.root, conn._logger)
assert_equal('guest', conn._user)
assert_equal('guest', conn._password)
assert_equal('localhost', conn._host)
assert_equal(5672, conn._port)
assert_equal('/', conn._vhost)
assert_equal(5, conn._connect_timeout)
assert_equal(None, conn._sock_opts)
assert_equal(None, conn._sock)
assert_equal(None, conn._heartbeat)
assert_equal(None, conn._open_cb)
assert_equal(None, conn._close_cb)
assert_equal('AMQPLAIN', conn._login_method)
assert_equal('en_US', conn._locale)
assert_equal(None, conn._client_properties)
assert_equal(conn._properties, {
'library': 'Haigha',
'library_version': __version__,
})
assert_false(conn._closed)
assert_false(conn._connected)
assert_equal(conn._close_info, {
'reply_code': 0,
'reply_text': 'first connect',
'class_id': 0,
'method_id': 0
})
assert_equals({
20: ChannelClass,
40: ExchangeClass,
50: QueueClass,
60: BasicClass,
90: TransactionClass
}, conn._class_map)
assert_equal({0: 'connection_channel'}, conn._channels)
assert_equal('\x05LOGINS\x00\x00\x00\x05guest\x08PASSWORDS\x00\x00\x00\x05guest',
conn._login_response)
assert_equal(0, conn._channel_counter)
assert_equal(65535, conn._channel_max)
assert_equal(65535, conn._frame_max)
assert_equal([], conn._output_frame_buffer)
assert_equal(transport, conn._transport)
transport.synchronous = True
assert_false(conn._synchronous)
assert_true(conn.synchronous)
assert_true(conn._synchronous_connect)
示例5: start
def start(self, **kwargs):
self.connection = Connection(**kwargs)
self.channel = self.connection.channel()
self.loop = TaskLoop()
self.insert_task(self.read_frames, interval=0.01)
self.insert_task(self.__run)
self.loop.start()
示例6: __clear__
def __clear__(args):
bus_ip, bus_port, vhost, username, password, exchange, queue, routing_key, durable = args
conn = Connection(user=username, password=password, host=bus_ip, port=bus_port, vhost=vhost)
counter, timeout_time = 0, time.time()+1
try:
ch = conn.channel()
ch.exchange.declare(exchange, 'direct')
ch.queue.declare(queue, durable=durable, auto_delete=False)
ch.queue.bind(queue, exchange, routing_key)
ch.basic.qos(prefetch_size=0, prefetch_count=1000)
while time.time() < timeout_time:
msg = ch.basic.get(queue)
if msg:
timeout_time = time.time() + 1
else:
time.sleep(0.01)
counter += 1
finally:
conn.close()
示例7: test_init_with_event_transport
def test_init_with_event_transport(self):
conn = Connection.__new__( Connection )
strategy = mock()
mock( connection, 'ConnectionChannel' )
expect(connection.ConnectionChannel).args( conn, 0, {} ).returns( 'connection_channel' )
expect(event_transport.EventTransport).args( conn ).returns( 'EventTransport' )
expect(conn.connect).args( 'localhost', 5672 )
conn.__init__(transport='event')
示例8: __init__
def __init__(self):
self.connection = Connection(host='localhost', heartbeat=None, debug=True)
self.channel = self.connection.channel()
result = self.channel.queue.declare(exclusive=True)
self.callback_queue = result[0]
print("callback_queue:", self.callback_queue)
self.channel.basic.consume(self.callback_queue, self.on_response, no_ack=True)
示例9: driver_main
def driver_main(name, bus_ip, bus_port, vhost, username, password, exchange, req_routing_key,
req_msg_list, send_interval, report_queue, state, codec):
assert_is_instance(send_interval, float)
assert_greater_equal(send_interval, 0.0)
conn, next_log_time, req_num = None, 0, 0
try:
conn = Connection(user=username, password=password, host=bus_ip, port=bus_port, vhost=vhost)
pch = conn.channel()
report_queue.put((name, 0, ProcessStarted, None))
#waiting for tester set state to 1(means to start test)
while StateInit == state.value:
time.sleep(0.01)
eq_(StateRunning, state.value)
req_num, total_sent = 0, 0
start_time = time.time()
next_send_time = start_time + send_interval
next_log_time = int(start_time) + 1
for app_msg in req_msg_list:
if 0 < send_interval:
dt = next_send_time - time.time()
if dt > 0.0:
time.sleep(dt)
pch.basic.publish(Message(app_msg), exchange, req_routing_key)
next_send_time += send_interval
req_num += 1
if time.time() >= next_log_time:
report_queue.put((name, next_log_time, DriverReqReport, (req_num,)))
total_sent += req_num
req_num = 0
next_log_time += 1
if StateRunning != state.value: break
except KeyboardInterrupt as e:
pass
finally:
total_sent += req_num
print name + ': end of loop, total %d msgs sent'%total_sent
report_queue.put((name, next_log_time, DriverReqReport, (req_num,)))
report_queue.put((name, next_log_time, DriverEndNotice, (total_sent,)))
if conn:
conn.close()
示例10: _connect_to_broker
def _connect_to_broker(self):
''' Connect to broker and regisiter cleanup action to disconnect
:returns: connection instance
:rtype: `haigha.connection.Connection`
'''
sock_opts = {
(socket.IPPROTO_TCP, socket.TCP_NODELAY) : 1,
}
connection = Connection(
logger=_LOG,
debug=_OPTIONS.debug,
user=_OPTIONS.user,
password=_OPTIONS.password,
vhost=_OPTIONS.vhost,
host=_OPTIONS.host,
heartbeat=None,
sock_opts=sock_opts,
transport='socket')
self.addCleanup(lambda: connection.close(disconnect=True)
if not connection.closed else None)
return connection
示例11: test_init_without_keyword_args
def test_init_without_keyword_args(self):
conn = Connection.__new__( Connection )
strategy = mock()
mock( connection, 'ConnectionChannel' )
mock( connection, 'ConnectionStrategy' )
expect(connection.ConnectionChannel).args( conn, 0 ).returns( 'connection_channel' )
expect(connection.ConnectionStrategy).args( conn, 'localhost', reconnect_cb=None ).returns( strategy )
expect(strategy.connect)
conn.__init__()
self.assertFalse( conn._debug )
self.assertEqual( logging.root, conn._logger )
self.assertEqual( 'guest', conn._user )
self.assertEqual( 'guest', conn._password )
self.assertEqual( 'localhost', conn._host )
self.assertEqual( '/', conn._vhost )
self.assertEqual( 5, conn._connect_timeout )
self.assertEqual( None, conn._sock_opts )
self.assertEqual( None, conn._sock )
self.assertEqual( None, conn._heartbeat )
self.assertEqual( None, conn._reconnect_cb )
self.assertEqual( None, conn._close_cb )
self.assertEqual( 'AMQPLAIN', conn._login_method )
self.assertEqual( 'en_US', conn._locale )
self.assertEqual( None, conn._client_properties )
self.assertEqual( conn._properties, {
'library': 'Haigha',
'library_version': VERSION,
} )
self.assertFalse( conn._closed )
self.assertFalse( conn._connected )
self.assertEqual( conn._close_info, {
'reply_code' : 0,
'reply_text' : 'first connect',
'class_id' : 0,
'method_id' : 0
} )
self.assertEqual( {0:'connection_channel'}, conn._channels )
self.assertEqual( '\x05LOGINS\x00\x00\x00\x05guest\x08PASSWORDS\x00\x00\x00\x05guest', conn._login_response )
self.assertEqual( 0, conn._channel_counter )
self.assertEqual( 65535, conn._channel_max )
self.assertEqual( 65535, conn._frame_max )
self.assertEqual( strategy, conn._strategy )
self.assertEqual( None, conn._output_buffer )
self.assertEqual( [], conn._output_frame_buffer )
示例12: setUp
def setUp(self):
super(ConnectionTest,self).setUp()
self.connection = Connection.__new__( Connection )
self.connection._debug = False
self.connection._logger = self.mock()
self.connection._user = 'guest'
self.connection._password = 'guest'
self.connection._host = 'localhost'
self.connection._vhost = '/'
self.connection._connect_timeout = 5
self.connection._sock_opts = None
self.connection._sock = None # mock anything?
self.connection._heartbeat = None
self.connection._open_cb = self.mock()
self.connection._close_cb = self.mock()
self.connection._login_method = 'AMQPLAIN'
self.connection._locale = 'en_US'
self.connection._client_properties = None
self.connection._properties = {
'library': 'Haigha',
'library_version': 'x.y.z',
}
self.connection._closed = False
self.connection._connected = False
self.connection._close_info = {
'reply_code' : 0,
'reply_text' : 'first connect',
'class_id' : 0,
'method_id' : 0
}
self.connection._class_map = {}
self.connection._channels = {
0 : self.mock()
}
self.connection._login_response = 'loginresponse'
self.connection._channel_counter = 0
self.connection._channel_max = 65535
self.connection._frame_max = 65535
self.connection._frames_read = 0
self.connection._frames_written = 0
self.connection._strategy = self.mock()
self.connection._output_frame_buffer = []
self.connection._transport = mock()
self.connection._synchronous = False
self.connection._synchronous_connect = False
示例13: start
def start(self):
self._connection = Connection(
transport='gevent',
user='guest', password='guest',
vhost=self.vhost, host=self.queueServer,
heartbeat=None, debug=True)
self._channel = self._connection.channel()
self._channel.add_close_listener(self._channel_closed_cb)
# Create and configure message exchange and queue
print self.exchange
print self.queueName
self._channel.exchange.declare(self.exchange, 'topic')
self._channel.queue.declare(self.queueName, auto_delete=False)
self._channel.queue.bind(self.queueName, self.exchange, self.queueName)
self._channel.basic.consume(queue=self.queueName,
consumer=self._process_message)
# Start message pump
self.running = True
self._message_pump_greenlet = gevent.spawn(self._message_pump_greenthread)
print "Started"
示例14: Connection
import sys
from haigha.connection import Connection
from haigha.message import Message
sys.path.append("/home/ec2-user/source/Quant/component")
import rdm
r = rdm.RedisInfo()
connection = Connection(
host=r.rmq['hostname'], port=r.rmq['port'],
user=r.rmq['user'], password=r.rmq['pass'],
vhost='/', heartbeat=None, debug=True)
ch = connection.channel()
ch.exchange.declare('test_exchange', 'direct')
ch.queue.declare('test_queue', auto_delete=True)
ch.queue.bind('test_queue', 'test_exchange', 'test_key')
ch.basic.publish( Message('body', application_headers={'hello':'world'}), exchange='test_exchange', routing_key='test_key' )
mq = ch.basic.get('test_queue')
connection.close()
print mq
示例15: run
def run(self):
"""Thread with connection to rabbitmq"""
if config.RABBITMQ_LOOPBACK:
self.logger.warning("Looopback mode: No connection, waiting for ever...")
while True:
time.sleep(1)
while True:
try:
time.sleep(1)
self.logger.debug("Connecting to RabbitMQ (user=%s,host=%s,port=%s,vhost=%s)" % (
config.RABBITMQ_USER, config.RABBITMQ_HOST, config.RABBITMQ_PORT, config.RABBITMQ_VHOST))
self.cox = Connection(user=config.RABBITMQ_USER, password=config.RABBITMQ_PASSWORD,
vhost=config.RABBITMQ_VHOST, host=config.RABBITMQ_HOST, port=config.RABBITMQ_PORT,
debug=config.RABBITMQ_DEBUG)
self.logger.debug("Creating the channel")
self.ch = self.cox.channel()
# Name will come from a callback
global queue_name
queue_name = None
def queue_qb(queue, msg_count, consumer_count):
self.logger.debug("Created queue %s" % (queue,))
global queue_name
queue_name = queue
self.logger.debug("Creating the queue")
if not self.watchdog:
# 'Normal', tempory queue
self.ch.queue.declare(auto_delete=True, nowait=False, cb=queue_qb)
else:
# Persistant queue, if not in test mode
if len(sys.argv) > 1 and sys.argv[1] == '--test':
self.ch.queue.declare(config.FB_QUEUE, auto_delete=True, nowait=False, cb=queue_qb)
else:
self.ch.queue.declare(config.FB_QUEUE, auto_delete=False, nowait=False, cb=queue_qb)
for i in range(0, 10): # Max 10 seconds
if queue_name is None:
time.sleep(1)
if queue_name is None:
self.logger.warning("Queue creation timeout !")
raise Exception("Cannot create queue !")
self.logger.debug("Binding the exchange %s" % (config.RABBITMQ_EXCHANGE,))
self.ch.queue.bind(queue_name, config.RABBITMQ_EXCHANGE, '')
self.logger.debug("Binding the comsumer")
self.ch.basic.consume(queue_name, self.consumer)
self.logger.debug("Ready, waiting for events !")
while True:
if not hasattr(self.ch, 'channel') or (
hasattr(self.ch.channel, '_closed') and self.ch.channel._closed):
self.logger.warning("Channel is closed")
raise Exception("Connexion or channel closed !")
self.cox.read_frames()
except Exception as e:
self.logger.error("Error in run: %s" % (e,))
finally:
if self.cox is not None:
self.cox.close()