本文整理汇总了Python中kombu.Exchange.declare方法的典型用法代码示例。如果您正苦于以下问题:Python Exchange.declare方法的具体用法?Python Exchange.declare怎么用?Python Exchange.declare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kombu.Exchange
的用法示例。
在下文中一共展示了Exchange.declare方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_assert_is_bound
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def test_assert_is_bound(self):
exchange = Exchange('foo', 'direct')
with self.assertRaises(NotBoundError):
exchange.declare()
conn = get_conn()
chan = conn.channel()
exchange.bind(chan).declare()
self.assertIn('exchange_declare', chan)
示例2: test_assert_is_bound
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def test_assert_is_bound(self):
exchange = Exchange('foo', 'direct')
with pytest.raises(NotBoundError):
exchange.declare()
conn = get_conn()
chan = conn.channel()
exchange.bind(chan).declare()
assert 'exchange_declare' in chan
示例3: connect_to_amqp
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def connect_to_amqp(sysconfig):
"""
Connect to an AMQP Server, and return the connection and Exchange.
:param sysconfig: The slickqaweb.model.systemConfiguration.amqpSystemConfiguration.AMQPSystemConfiguration instance
to use as the source of information of how to connect.
:return: (connection, exchange) on success, exception on error
"""
assert isinstance(sysconfig, AMQPSystemConfiguration)
configuration = dict()
configuration['AMQP'] = dict()
if hasattr(sysconfig, 'hostname') and sysconfig.hostname is not None:
configuration['AMQP']['hostname'] = sysconfig.hostname
else:
raise AMQPConnectionError(message="No hostname defined for AMQP connection.")
if hasattr(sysconfig, 'port') and sysconfig.port is not None:
configuration['AMQP']['port'] = sysconfig.port
if hasattr(sysconfig, 'username') and sysconfig.username is not None:
configuration['AMQP']['username'] = sysconfig.username
if hasattr(sysconfig, 'password') and sysconfig.password is not None:
configuration['AMQP']['password'] = sysconfig.password
if hasattr(sysconfig, 'virtualHost') and sysconfig.virtualHost is not None:
configuration['AMQP']['virtual host'] = sysconfig.virtualHost
if hasattr(sysconfig, 'exchangeName') and sysconfig.exchangeName is not None:
configuration['AMQP']['exchange'] = sysconfig.exchangeName
else:
raise AMQPConnectionError(message="No exchange defined for AMQP connection.")
logger = logging.getLogger("slickqaweb.amqpcon.connect_to_amqp")
url = str.format("amqp://{hostname}:{port}", **dict(list(configuration['AMQP'].items())))
if 'virtual host' in configuration['AMQP'] and configuration['AMQP']['virtual host'] != '':
url = str.format("{}/{}", url, configuration['AMQP']['virtual host'])
logger.debug("AMQPConnection configured with url %s", url)
exchange = Exchange(configuration['AMQP'].get('exchange', "amqp.topic"), type='topic', durable=True)
logger.debug("AMQPConnection is using exchange %s", exchange)
connection = None
if 'username' in configuration['AMQP'] and 'password' in configuration['AMQP']:
username = configuration['AMQP']['username']
password = configuration['AMQP']['password']
logger.debug("Using username %s and password %s to connect to AMQP Broker", username, password)
connection = Connection(url, userid=username, password=password)
else:
connection = Connection(url)
# typically connection connect on demand, but we want to flush out errors before proceeding
connection.connect()
exchange = exchange(connection)
exchange.declare()
return (connection, exchange)
示例4: broker
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
class SocketBrokerClient:
"""
Base class for web socket notification using broker (redis or rabbitmq)
"""
connection = None
def __init__(self, url, exchange_name=None):
self.url = url
self.connect()
self.exchange_name = exchange_name if exchange_name else celery_queue('socket_notification')
self.channel = self.connection.channel()
self.socket_exchange = Exchange(self.exchange_name, type='fanout', channel=self.channel)
self.socket_exchange.declare()
def open(self):
"""Test if connection is open.
True if connected else false
:return bool:
"""
return self.connection and self.connection.connected
def connect(self):
self._close()
logger.info('Connecting to broker {}'.format(self.url))
self.connection = Connection(self.url, heartbeat=WS_HEART_BEAT)
self.connection.connect()
logger.info('Connected to broker {}'.format(self.url))
def _close(self):
if hasattr(self, 'connection') and self.connection:
logger.info('Closing connecting to broker {}'.format(self.url))
self.connection.release()
self.connection = None
logger.info('Connection closed to broker {}'.format(self.url))
def close(self):
self._close()
示例5: broker
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
class SocketBrokerClient:
"""
Base class for web socket notification using broker (redis or rabbitmq)
"""
connection = None
def __init__(self, url):
self.url = url
self.connect()
self.channel = self.connection.channel()
self.socket_exchange = Exchange(exchange_name, type="fanout", channel=self.channel)
self.socket_exchange.declare()
def open(self):
"""
True if connected else false
:return bool:
"""
return self.connection and self.connection.connected
def connect(self):
self._close()
logger.info("Connecting to broker {}".format(self.url))
self.connection = Connection(self.url)
self.connection.connect()
logger.info("Connected to broker {}".format(self.url))
def _close(self):
if hasattr(self, "connection") and self.connection:
logger.info("Closing connecting to broker {}".format(self.url))
self.connection.release()
self.connection = None
logger.info("Connection closed to broker {}".format(self.url))
def close(self):
self._close()
示例6: declare_exchange
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def declare_exchange(self, name, type='direct', queues=None, **options):
"""Create or update exchange
:param name: name of exchange
:type name: str
:param type: type of exchange - direct, fanout, topic, match
:type type: str
:param queues: list of queues with routing keys: [[queue_name, routing_key], [queue_name, routing_key], ...]
:type queues: list, None or tuple
:param options: additional options for Exchange creation
"""
if queues is None:
queues = []
with connections[self.connection].acquire() as conn:
exchange = Exchange(name, type=type, channel=conn, **options)
exchange.declare()
self.exchanges[name] = exchange
for q_name, routing_key in queues:
queue = Queue(name=q_name, channel=conn)
queue.declare()
queue.bind_to(exchange=name, routing_key=routing_key)
self.logger.debug('Queue "%s" with routing_key "%s" was bond to exchange "%s"', q_name,
routing_key if routing_key else q_name, name)
示例7: connect
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def connect(self):
if not self.connection:
logging.info("Connecting to server %s", self.amqp_address)
self.connection = self.create_connection()
else:
return
self.channel = self.connection.channel()
self.channel.basic_qos(0, self.prefetch_count, False)
for qname, params in self.queues.iteritems():
if "exchange" in params:
exchange = Exchange(params["exchange"], **self.exchanges.get(params["exchange"], {}))
exchange = exchange(self.channel)
exchange.declare()
self.declared_exchanges[params["exchange"]] = exchange
queue_params = params.copy()
del queue_params['exchange']
self.declared_queues[qname] = Queue(qname, exchange=exchange, **queue_params)
else:
self.declared_queues[qname] = Queue(qname, **params)
self.declared_queues[qname](self.channel).declare()
示例8: KWriteQueue
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
class KWriteQueue(object):
def __init__(self, channel, exchange, **kwargs):
self._exchange_declare = kwargs.get("exchange_declare", False)
if isinstance(exchange, Queue):
self.exchange = exchange.exchange
elif isinstance(exchange, basestring):
self.exchange = Exchange(exchange, type="fanout") # , durable=True)
else:
assert isinstance(exchange, Exchange)
self.exchange = exchange
self.channel = maybe_channel(channel)
self.exchange.maybe_bind(self.channel)
if self._exchange_declare:
self.exchange.declare()
self.producer = messaging.Producer(channel, self.exchange,
serializer='json',
routing_key='',
compression=None,
auto_declare=False)
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
def put(self, message, serializer=None, headers=None, compression=None,
routing_key=None, **kwargs):
self.producer.publish(message,
content_type="application/octet-stream",
serializer=serializer,
routing_key=routing_key,
headers=headers,
compression=compression,
**kwargs)
示例9: _declare_exchange
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def _declare_exchange(self, name, type, retry=False, retry_policy={}):
ex = Exchange(name, type=type, durable=self.durable,
auto_delete=self.auto_delete)(self.channel)
if retry:
return self.connection.ensure(ex, ex.declare, **retry_policy)
return ex.declare()
示例10: handle_message
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def handle_message(body, message):
print('Received message: %r' % (body, ))
print(' properties:\n%s' % (pretty(message.properties), ))
print(' delivery_info:\n%s' % (pretty(message.delivery_info), ))
message.ack()
#: Create a connection and a channel.
#: If hostname, userid, password and virtual_host is not specified
#: the values below are the default, but listed here so it can
#: be easily changed.
with Connection('pyamqp://guest:[email protected]:5672//') as connection:
# The configuration of the message flow is as follows:
# gateway_kombu_exchange -> internal_kombu_exchange -> kombu_demo queue
gateway_exchange = Exchange('gateway_kombu_demo')(connection)
exchange = Exchange('internal_kombu_demo')(connection)
gateway_exchange.declare()
exchange.declare()
exchange.bind_to(gateway_exchange, routing_key='kombu_demo')
queue = Queue('kombu_demo', exchange, routing_key='kombu_demo')
#: Create consumer using our callback and queue.
#: Second argument can also be a list to consume from
#: any number of queues.
with Consumer(connection, queue, callbacks=[handle_message]):
#: This waits for a single event. Note that this event may not
#: be a message, or a message that is to be delivered to the consumers
#: channel, but any event received on the connection.
recv = eventloop(connection)
while True:
示例11: BrokerConnection
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
import boto
from kombu import BrokerConnection, Exchange, Queue, Consumer
connection = BrokerConnection()
connection.connect()
channel = connection.channel()
exchange = Exchange(name="android", type="fanout", channel=channel, durable=True)
exchange.declare()
channel = connection.channel()
queue = Queue(name="filr", exchange=exchange, durable=True, auto_delete=False, channel=channel, routing_key="filr")
queue.declare()
def fetch(b, m):
print b, m
consumer = Consumer(channel=connection.channel(), queues=queue, auto_declare=False, callbacks=[fetch])
consumer.consume(no_ack=False)
while True:
connection.drain_events()
pass
# execfile('.private-settings')
# sdb = boto.connect_sdb(key_id, sec_key)
# domain = sdb.create_domain('android')
# item = domain.new_item('kral_step1')
示例12: Connection
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
import datetime
import threading
from twisted.internet import protocol, reactor, defer
from kombu import Exchange, Queue, Consumer, Connection
from kombu.messaging import Producer
from kombu.transport.base import Message
from kombu.common import eventloop, drain_consumer
from kombu.async import Hub
connection = Connection('amqp://guest:[email protected]//')
channel = connection.channel()
# 定义了一个exchange
task_exchange = Exchange('tasks', channel=channel, type='topic', durable=False)
task_exchange.declare()
# 在这里进行了exchange和queue的绑定,并且指定了这个queue的routing_key
task_queue = Queue('piap', task_exchange, channel=channel,
routing_key='suo_piao.#', durable=False)
task_queue2 = Queue('piap2.*abc.#', task_exchange, channel=channel,
routing_key='suo_piao.#', durable=False)
task_queue3 = Queue('piap3', task_exchange, channel=channel,
routing_key='suo_piao.abc.#', durable=False)
task_queue4 = Queue('piap4', task_exchange, channel=channel,
routing_key='abc.#', durable=False)
task_queues = []
for x in xrange(1,10):
tmpQueue = Queue('testFlood'+str(x), task_exchange, channel=channel,
routing_key='abc.*.'+str(x), durable=False)
tmpQueue.declare()
示例13: process_media
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
def process_media(body, message):
print '*'*10
print body
print '*'*10
message.ack()
# Connection
conn = Connection('amqp://[email protected]//')
channel = conn.channel()
media_exchange = Exchange('media', 'topic', channel=channel, durable=True)
video_queue = Queue('video', channel=channel, exchange=media_exchange, routing_key='video')
try:
media_exchange.declare()
except amqp.exceptions.PreconditionFailed, e:
print 'zhe...'
print e
exit()
# produce
producer = conn.Producer(serializer='json', auto_declare=False)
producer.publish('name',
exchange = media_exchange, routing_key='video',
declare=[video_queue])
# # consume
# with conn.Consumer(video_queue, callbacks=[process_media]) as consumer:
# while True:
示例14: Publisher
# 需要导入模块: from kombu import Exchange [as 别名]
# 或者: from kombu.Exchange import declare [as 别名]
class Publisher(KombuConfReader):
def __init__(self, config):
self._log = log.getLogger()
KombuConfReader.__init__(self, config)
self.connection = Connection(self.broker_url)
try:
self._init_amqp()
except Exception as exc:
self._log.error('Publisher fail in init connection: %s' % exc)
raise
def _init_amqp(self):
"""Init AMQP objects after connection"""
self.producer = self.connection.Producer()
self.exchange = Exchange(
self.exchange_name,
channel=self.connection.channel(),
type=self.exchange_type,
durable=self.exchange_is_durable)
self.queue = Queue(
self.queue_name,
self.exchange,
channel=self.connection.channel(),
durable=self.queue_is_durable,
routing_key=self.routing_key,
queue_arguments=self.queue_args)
# We declare object to broker. this way only we can
# ensure to publish to an existing queue and routing_key
# AMQP work this way, not a library principle
self.exchange.declare()
self.queue.declare()
def switch_connection(self):
"""Switch AMQP connection from url to backup_url and vice versa"""
self._log.warn('Switching AMQP connection from %s' %
self.connection.as_uri())
if (self.connection.hostname in self.broker_url
and self.broker_backup_url):
self.connection = Connection(self.broker_backup_url)
elif self.connection.hostname in self.broker_backup_url:
self.connection = Connection(self.broker_url)
else:
raise URLError('Invalid current URI to switch connection : %s' %
self.connection.as_uri())
self._init_amqp()
def _publish(self, msg):
"""Publish message ensuring connection is available"""
publish = self.connection.ensure(
self.producer, self.producer.publish, max_retries=3)
publish(msg, exchange=self.exchange,
routing_key=self.routing_key,
serializer=self.serializer,
compression=self.compression)
return True
def publish(self, msg):
"""
must return True/False if message is well publish or not
"""
try:
return self._publish(msg)
except Exception as exc:
try:
self.switch_connection()
return self._publish(msg)
except Exception as exc:
self._log.error('Publish fail when switching connection: %s' %
exc)
return False