本文整理汇总了Python中pika.adapters.SelectConnection类的典型用法代码示例。如果您正苦于以下问题:Python SelectConnection类的具体用法?Python SelectConnection怎么用?Python SelectConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SelectConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BaseAMQPConnection
class BaseAMQPConnection(BaseConnection):
""" An object which does an actual job of (re-)connecting to the the AMQP broker.
Concrete subclasses implement either listening or publishing features.
"""
def __init__(self, conn_params, item_name, properties=None):
super(BaseAMQPConnection, self).__init__()
self.conn_params = conn_params
self.item_name = item_name
self.properties = properties
self.conn = None
self.channel = None
self.reconnect_exceptions = (TypeError, EnvironmentError)
def _start(self):
self.conn = SelectConnection(self.conn_params, self._on_connected)
self.conn.ioloop.start()
def _close(self):
""" Actually close the connection.
"""
if self.conn:
try:
self.conn.close()
except socket.error, e:
if e.errno != errno.EBADF:
# EBADF meant we actually had a connection but it was unusable (like the credentials were incorrect)
raise
示例2: connect
def connect(self, forever=False):
name = self.name
while True:
try:
connection = SelectConnection(
self.parameters, self.on_connected)
log.debug('%s connected', name)
except Exception:
if not forever:
raise
log.warning('%s cannot connect', name, exc_info=True)
time.sleep(10)
continue
try:
connection.ioloop.start()
finally:
try:
connection.close()
connection.ioloop.start() # allow connection to close
except Exception:
pass
if not forever:
break
示例3: start
def start(self):
# parameters require for the AMQP connection: user name and password...
credentials = PlainCredentials(RabbitMQConfiguration().getRabbitMQProperty("gameLogicServerUserName"),
RabbitMQConfiguration().getRabbitMQProperty("gameLogicServerUserName"))
parameters = pika.ConnectionParameters(host=RabbitMQConfiguration().getRabbitMQProperty("gameLogicServerBrokerHost"),
virtual_host=self.state.vhost,
credentials=credentials)
# instantiate a connection
connection = SelectConnection(parameters=parameters,
on_open_callback=self.on_connected)
# required behavior on close
connection.add_on_close_callback(self.on_close)
# start the connection
connection.ioloop.start()
示例4: __init__
def __init__(self, config):
self.delivery_conn = None
self.delivery_channel = None
self.notifs_conn = None
self.notifs_channel = None
# Extract configuration
self.broker_username = config['broker.username']
self.broker_password = config['broker.password']
self.broker_host = config['broker.host']
self.broker_amqp_port = config['broker.amqp_port']
self.broker_http_port = config['broker.http_port']
self.broker_vhost = config['broker.vhost']
self.incoming_exchange_name = config['broker.incoming_exchange_name']
self.notifs_queue_name = config['broker.notifications_queue_name']
# Create connection parameters object for easy reuse
self.conn_params = pika.ConnectionParameters(
credentials=pika.PlainCredentials(
self.broker_username,
self.broker_password,
),
host=self.broker_host,
port=self.broker_amqp_port,
virtual_host=self.broker_vhost,
)
self.notifs_conn = SelectConnection(
self.conn_params,
self.on_notifs_connected,
)
示例5: testnb
def testnb():
node = NodeNB()
#ch = node.channel(('amq.direct', 'foo'), TestServer)
ch = node.channel(TestServer)
#ch = node.channel(TestClient)
conn_parameters = ConnectionParameters()
connection = SelectConnection(conn_parameters , node.on_connection_open)
# Loop until CTRL-C
try:
# Start our blocking loop
connection.ioloop.start()
except KeyboardInterrupt:
# Close the connection
connection.close()
# Loop until the connection is closed
connection.ioloop.start()
示例6: simple_server
def simple_server(ca_certs, keyfile, certfile, host_name, use_ssl):
host = host_name
if use_ssl:
ssl_opts = {'ca_certs': ca_certs,
'keyfile': keyfile,
'certfile': certfile,
'cert_reqs': ssl.CERT_REQUIRED}
port = 5671
else:
ssl_opts = None
port = 5672
parameters = ConnectionParameters(host, port,
ssl=use_ssl, ssl_options=ssl_opts)
connection = SelectConnection(parameters, on_connected)
# Loop until CTRL-C
try:
# Start our blocking loop
connection.ioloop.start()
except KeyboardInterrupt:
# Close the connection
connection.close()
# Loop until the connection is closed
connection.ioloop.start()
示例7: connect
def connect(self):
if self.connecting:
return
self.connecting = True
credentials = pika.PlainCredentials('guest', 'guest')
params = pika.ConnectionParameters(host="hackinista.com",
port=5672,
virtual_host="/",
credentials=credentials)
host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1'
try:
self.connection = SelectConnection(params, self.on_connected)
except:
# self.L.critical("Error connecting to rabbitmq on host =
# "+self.host);
sys.exit(-1)
示例8: connect
def connect(self):
print self
if self.connecting:
print ('1...PikaClient: Already connecting to RabbitMQ')
return
print ('1...PikaClient: Connecting to RabbitMQ on localhost:5672')
self.connecting = True
credentials = pika.PlainCredentials('guest', 'guest')
param = pika.ConnectionParameters(host='localhost',
port=5672,
virtual_host="/",
credentials=credentials)
host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1'
self.connection = SelectConnection(ConnectionParameters(host),
self.on_connected)
if self.connection != None:
print self.connection
print 'connection'
示例9: SelectConnection
routing_key="krqueue",
body=jsonmsg,
properties=properties)
print "demo_send:" + jsonmsg
# Close our connection
print "Closing client"
connection.close()
if __name__ == '__main__':
pika.log.setup(level=pika.log.INFO)
# Connect to RabbitMQ
host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1'
connection = SelectConnection(ConnectionParameters(host),
on_connected)
# Loop until CTRL-C
try:
# Start our blocking loop
connection.ioloop.start()
except KeyboardInterrupt:
# Close the connection
connection.close()
# Loop until the connection is closed
connection.ioloop.stop()
示例10: __init__
def __init__(self, parameters=None, on_open_callback=None,
reconnection_strategy=None):
SelectConnection.__init__(self, parameters=parameters, on_open_callback=on_open_callback, reconnection_strategy=reconnection_strategy)
self._bad_channel_numbers = set()
self._pending = set()
示例11: _start
def _start(self):
self.conn = SelectConnection(self.conn_params, self._on_connected)
self.conn.ioloop.start()
示例12: dataChannel
class dataChannel(object):
""" The dataChannel is the base class of all our datasource.
It's purpose is to: a). Setup the queues"""
def __init__(self, server_name='test', mq_exchange='', mq_queue = '',mq_host=''):
self.channel = None
self.id = server_name
self.queue_counter = 0
self.queue =mq_queue
self.routing_key = ''
self.exchange = mq_exchange
self.connection = None
self.connected = False
self.connecting = False
self.rabbithost = mq_host
logging.getLogger('pika').setLevel(logging.DEBUG)
def get_connection(self):
return self.connection
def connect(self):
if self.connecting:
return
self.connecting = True
credentials = pika.PlainCredentials('guest', 'guest')
params = pika.ConnectionParameters(host="hackinista.com",
port=5672,
virtual_host="/",
credentials=credentials)
host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1'
try:
self.connection = SelectConnection(params, self.on_connected)
except:
# self.L.critical("Error connecting to rabbitmq on host =
# "+self.host);
sys.exit(-1)
###
def on_connected(self, connection):
self.connection = connection
self.connection.channel(self.on_channel_open)
self.connected = True
def on_channel_open(self, channel):
self.channel = channel
try:
self.channel.queue_declare(queue=self.queue,
auto_delete=False,
durable=True,
exclusive=False,
callback=self.on_queue_declared)
except:
print "Error declaring queue = " + self.queue
sys.exit(-1)
def on_queue_declared(self, frame):
try:
self.channel.queue_bind(exchange=self.exchange,
queue=self.queue,
routing_key=self.routing_key,
callback=self.on_queue_bound)
except:
print "Binding to queue = " + self.queue
pass
def on_queue_bound(self, frame):
self.channel.basic_consume(consumer_callback=self.handle_delivery,
queue=self.queue, no_ack=False)
def handle_delivery(self, channel, method_frame, header_frame, body):
print "7...Basic.Deliver %s delivery-tag %i: %s" %\
(header_frame.content_type,
method_frame.delivery_tag,
body)
self.data_op(body)
channel.basic_ack(delivery_tag=method_frame.delivery_tag)
def data_op(self, args):
print "Please implement get_data"
示例13: RouterServer
class RouterServer(object):
"""Validates and routes notifications.
This acts as a separate server used only for production systems.
In a development environment, the post office performs the validation
itself, however this does not allow it to scale in situations where
a large spike of requests come in (as the requests take longer to
complete when validation is performed). Thus in production the post
office simply dumps messages into queue which are then consumed,
validated, and then routed to their destination.
"""
def __init__(self, config):
self.delivery_conn = None
self.delivery_channel = None
self.notifs_conn = None
self.notifs_channel = None
# Extract configuration
self.broker_username = config['broker.username']
self.broker_password = config['broker.password']
self.broker_host = config['broker.host']
self.broker_amqp_port = config['broker.amqp_port']
self.broker_http_port = config['broker.http_port']
self.broker_vhost = config['broker.vhost']
self.incoming_exchange_name = config['broker.incoming_exchange_name']
self.notifs_queue_name = config['broker.notifications_queue_name']
# Create connection parameters object for easy reuse
self.conn_params = pika.ConnectionParameters(
credentials=pika.PlainCredentials(
self.broker_username,
self.broker_password,
),
host=self.broker_host,
port=self.broker_amqp_port,
virtual_host=self.broker_vhost,
)
self.notifs_conn = SelectConnection(
self.conn_params,
self.on_notifs_connected,
)
@wsgify
def __call__(self, request):
"""Allows router to be called directly by POST Office to perform
validation. Intended to simplify development -- SHOULD NOT be
used in a production system.
"""
try:
self.process_notification(request.body)
except KeyError as kerr:
raise HTTPBadRequest()
except Exception as ex:
raise HTTPInternalServerError()
return HTTPAccepted()
# XXX: Ugh...why must Pika be so difficult with multiple connections?
def start(self, blocking=True):
#Thread(target=self.delivery_conn.ioloop.start).start()
if blocking:
self.notifs_conn.ioloop.start()
else:
Thread(target=self.notifs_conn.ioloop.start).start()
def shutdown(self):
self.delivery_channel.close()
self.notifs_channel.close()
self.delivery_conn.close()
self.notifs_conn.close()
# Loop until everything shuts down
self.notifs_conn.ioloop.start()
def on_delivery_connected(self, connection):
connection.channel(self.on_delivery_channel_open)
def on_delivery_channel_open(self, channel):
self.delivery_channel = channel
def on_notifs_connected(self, connection):
connection.channel(self.on_notifications_channel_open)
# TODO: Figure out how to get 2 connections working in Pika.
# This is a hack for now, since we know we only have one broker.
self.on_delivery_connected(connection)
def on_notifications_channel_open(self, channel):
self.notifs_channel = channel
channel.queue_declare(
queue=self.notifs_queue_name,
durable=False,
exclusive=False,
auto_delete=False,
callback=self.on_notifications_queue_declared,
#.........这里部分代码省略.........
示例14: __init__
class dataChannel:
""" The dataChannel is the base class of all our datasource.
It's purpose is to: a). Setup the queues"""
def __init__(self,ds_name):
self.channel = None
self.dc_id = "eek"#dc_id
## query mongoDB to find all the particulars about this
## data channel including: which queue is listening to,
## which exchange, the routing key..etc.
self.ret_queue = "ret_queue"
self.connection = None
self.channel = None
self.connected = False;
self.connecting = False;
self.exchange = "test_x";
self.queue = "test_q"
self.routing_key = "test_q"
## use the ds to the find which exchange and which queue this
## datachannel listens
def mongo_db(self):
## connect to the mongodb
mongo_conn = Connection('localhost',27017)
db = mongo_conn['data_channels']
coll= db['bbox_pts']
def connect(self):
print self
if self.connecting:
print ('1...PikaClient: Already connecting to RabbitMQ')
return
print ('1...PikaClient: Connecting to RabbitMQ on localhost:5672')
self.connecting = True
credentials = pika.PlainCredentials('guest', 'guest')
param = pika.ConnectionParameters(host='localhost',
port=5672,
virtual_host="/",
credentials=credentials)
host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1'
self.connection = SelectConnection(ConnectionParameters(host),
self.on_connected)
if self.connection != None:
print self.connection
print 'connection'
def on_connected(self,connection):
print '2...PikaClient: Connected to RabbitMQ on localhost:5672'
self.connection = connection
self.connection.channel(self.on_channel_open)
self.connected = True
def on_channel_open(self, channel):
print ('3...PikaClient: Channel Open, Declaring Exchange')
self.channel = channel
self.channel.exchange_declare(exchange=self.exchange,
type="direct",
auto_delete=False,
durable=True,
callback=self.on_exchange_declared)
def on_exchange_declared(self, frame):
print ('4...PikaClient: Exchange Declared, Declaring Queue')
self.channel.queue_declare(queue=self.queue,
auto_delete=False,
durable=True,
exclusive=False,
callback=self.on_queue_declared)
def on_queue_declared(self, frame):
print('5...PikaClient: Queue Declared, Binding Queue')
print "demo_receive: Queue Declared"
# self.channel.basic_consume(self.handle_delivery, queue='test_q')
self.channel.queue_bind(exchange=self.exchange,
queue=self.queue,
routing_key=self.routing_key,
callback=self.on_queue_bound)
def on_queue_bound(self, frame):
print('6...PikaClient: Queue Bound, Issuing Basic Consume')
self.channel.basic_consume(consumer_callback=self.handle_delivery,
queue=self.queue)
def handle_delivery(self,channel, method_frame, header_frame, body):
print "7...Basic.Deliver %s delivery-tag %i: %s" %\
(header_frame.content_type,
method_frame.delivery_tag,
body)
print body
channel.basic_ack(delivery_tag=method_frame.delivery_tag)
def get_data(self,args):
print "Please implement get_data"
示例15: Amqp
class Amqp(object):
def __init__(self, conf):
# RabbitMQ general options
self.cacertfile = conf['cacertfile']
self.certfile = conf['certfile']
self.exchange = conf['exchange']
self.status_exchange = conf['status_exchange']
self.fail_if_no_peer_cert = conf['fail_if_no_peer_cert']
self.heartbeat = conf['heartbeat']
self.host = conf['host']
self.keyfile = conf['keyfile']
self.password = conf['password']
self.port = conf['port']
self.ssl_port = conf['ssl_port']
self.queue = conf['uuid']
self.retry_timeout = conf['retry_timeout']
self.ssl_auth = conf['ssl_auth']
self.use_ssl = conf['use_ssl']
self.username = conf['username']
self.vhost = conf['vhost']
# Connection and channel initialization
self.connection = None
self.channel = None
# Plain credentials
credentials = PlainCredentials(self.username, self.password)
pika_options = {'host': self.host,
'port': self.port,
'virtual_host': self.vhost,
'credentials': credentials}
# SSL options
if self.use_ssl:
pika_options['ssl'] = True
pika_options['port'] = self.ssl_port
if self.ssl_auth:
pika_options['credentials'] = ExternalCredentials()
pika_options['ssl_options'] = {
'ca_certs': self.cacertfile,
'certfile': self.certfile,
'keyfile': self.keyfile,
'cert_reqs': CERT_REQUIRED
}
if self.heartbeat:
pika_options['heartbeat'] = self.heartbeat
self.parameters = None
try:
self.parameters = pika.ConnectionParameters(**pika_options)
except TypeError as err:
self.logger.debug(err)
# Let's be compatible with original pika version (no integer for
# heartbeats and no ssl.
self.logger.warning("Wrong pika lib version, won't use ssl.")
pika_options['heartbeat'] = True
if self.use_ssl:
self.use_ssl = False
pika_options['port'] = self.port
del pika_options['ssl']
if self.ssl_auth:
self.ssl_auth = False
del pika_options['ssl_options']
self.parameters = pika.ConnectionParameters(**pika_options)
def connect(self):
SelectPoller.TIMEOUT = .1
self.connection = SelectConnection(self.parameters, self.on_connected)
self.connection.ioloop.start()
def close(self, amqperror=False):
if (self.connection and not self.connection.closing
and not self.connection.closed):
self.logger.debug("Closing connection")
self.connection.close()
#self.connection.ioloop.start()
def on_remote_close(self, code, text):
self.logger.debug("Remote channel close, code %d" % code)
time.sleep(2)
if code != 200:
self.close()
raise AmqpError(text)
def on_connection_closed(self, frame):
self.connection.ioloop.stop()
def on_connected(self, connection):
self.connection = connection
self.connection.add_on_close_callback(self.on_connection_closed)
self.connection.channel(self.on_channel_open)