当前位置: 首页>>代码示例>>Python>>正文


Python BlockingConnection.channel方法代码示例

本文整理汇总了Python中pika.BlockingConnection.channel方法的典型用法代码示例。如果您正苦于以下问题:Python BlockingConnection.channel方法的具体用法?Python BlockingConnection.channel怎么用?Python BlockingConnection.channel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pika.BlockingConnection的用法示例。


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

示例1: RabbitInput

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class RabbitInput(object):
    input_name = 'rabbitmq'

    def __init__(self, host, port=5672, vhost='/', username='guest', password='guest', queue='default', prefetch=10):
        credentials = PlainCredentials(username, password)
        self.connection_params = ConnectionParameters(host=host, port=port, virtual_host=vhost, credentials=credentials)
        self.queue = queue
        self.prefetch = prefetch

    def _worker(self, ch, method, properties, body):
        # TODO: find out why rabbitmq sucks
        if not body:
            logger.warning('empty message received from rabbitmq - skipping')
            ch.basic_ack(delivery_tag = method.delivery_tag)
            return 

        try:
            data = json.loads(body)
        except Exception as err:
            logger.debug('unable to decode json: %s' % (str(err), ))
        else:
            for fmt in self.format_modules:
                if fmt.bind and self.input_name in fmt.bind:
                    data = fmt.decode(data)

            self.output_threads.write(data)

        finally:
            ch.basic_ack(delivery_tag = method.delivery_tag)

    def handle_input(self):
        try:
            self.connection = BlockingConnection(self.connection_params)
            self.channel = self.connection.channel()

            self.channel.queue_declare(queue=self.queue, durable=True)
            self.channel.basic_qos(prefetch_count=self.prefetch)
            self.channel.basic_consume(self._worker, queue=self.queue)

            self.connection.channel()
            self.channel.start_consuming()
        except (AMQPConnectionError, socket.error) as err:
            raise EveConnectionError(err)


    def run(self, format_modules, output_modules):
        # Start output threads
        self.format_modules = format_modules
        self.output_modules = output_modules
        self.output_threads = OutputThreads(self.output_modules, self.format_modules)
        while True:
            try:
                self.handle_input()
            except EveConnectionError as err:
                logger.error('connection error in input handler %s: %r - retrying in 1 second' % (self.input_name, err))
                sleep(1)
开发者ID:Crapworks,项目名称:eve,代码行数:58,代码来源:rabbitmq.py

示例2: Publisher

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class Publisher(object):
    connection = None
    channel = None
    exchange = None

    def __init__(self, props):
        self.props = props

    def start(self, exchange):
        self.exchange = exchange
        self.connection = BlockingConnection()
        self.connection.set_backpressure_multiplier(self.props.backpressure)
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=exchange, durable=True, exclusive=False, auto_delete=False)

    def publish(self, status):
        self.channel.basic_publish(
            exchange="",
            routing_key=self.exchange,
            body=status,
            properties=BasicProperties(content_type="text/plain", delivery_mode=1),
        )

    def close(self):
        self.connection.close()
开发者ID:h4ck3rm1k3,项目名称:wpcorpus,代码行数:27,代码来源:rabbit.py

示例3: get_url_for_company_name

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
def get_url_for_company_name(ch, method, properties, body):
    """ lookup URL for a company using fortune's profile on the company """
    
    company_data = json.loads(body)
    company_name = company_data["name"]
    print " [x] Received %r" % (company_name)

    # hacks for slugfiying
    company_name_slug = company_name.lower().replace("& ", "").replace(".", "").replace(",", "").replace(" ", "-") 
    company_profile_url = "http://www.inc.com/inc5000/profile/%s" % company_name_slug

    r = requests.get(company_profile_url)
    soup = BeautifulSoup(r.text)

    detail_section = soup.find("div", "inc5000companydata")
    try:
        company_url = detail_section.find("a")["href"]
    except:
        company_url = None
        
    company_data["url"] = company_url
    to_send = json.dumps(company_data)
    ch.basic_ack(delivery_tag = method.delivery_tag)
    
    # now that we've gotten the company's URL, send the data to another worker to get the MG score
    connection = BlockingConnection(ConnectionParameters('localhost'))
    channel = connection.channel()
    channel.exchange_declare(exchange=EXCHANGE_NAME, type='direct')
    channel.basic_publish(exchange=EXCHANGE_NAME, routing_key='mg', body=to_send)
开发者ID:imclab,项目名称:py,代码行数:31,代码来源:get_inc_5000.py

示例4: Service

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class Service( object ):

    def __init__( self, topics, name, host = 'localhost', verbose = True, port = 5672, user = '', password = ''  ):
        credentials = PlainCredentials(user, password)
        self.connection = BlockingConnection( ConnectionParameters( host,  port, vhost, credentials ) )
        self.channel = self.connection.channel()
        self.channel.exchange_declare( exchange = exchange_name, type = 'topic' )
        self.queueID = self.channel.queue_declare( exclusive = True ).method.queue
        self.name = name

        for topic in topics:
            self.channel.queue_bind( exchange = exchange_name, queue = self.queueID, routing_key = topic)

    def _handle( self, c, m, p, b ):
        routingKey = self.name #'.'.join( [ 'SS', self.name ] )
        print routingKey, b
        self.channel.basic_publish( exchange = exchange_name, routing_key = routingKey, body = b)

    def close( self ):

        self.channel.stop_consuming()
        print 'done', datetime.datetime.now()
        #for key, val in self._deposit.iteritems():
        #    print key, len( val )

        self.connection.close()

    def run( self ):

        #_callback = lambda c, m, p, d: self._handle( d )
        self.channel.basic_consume( self._handle, queue = self.queueID, no_ack = True )
        self.channel.start_consuming()
开发者ID:jebuempak,项目名称:Quant,代码行数:34,代码来源:test_stateService.py

示例5: Service

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class Service( object ):

    def __init__( self, groups, host = 'localhost', verbose = True, port = 5672, user = '', password = '' ):
        credentials = PlainCredentials(user, password)
        self._connection = BlockingConnection( ConnectionParameters( host,  port, vhost, credentials ) )
        self._channel = self._connection.channel()
        self._channel.exchange_declare( exchange = exchange_name, type = 'topic' )
        self._queueID = self._channel.queue_declare( exclusive = True ).method.queue

        for topic in groups:
            self._channel.queue_bind(exchange = exchange_name, queue = self._queueID, routing_key = topic)
            
    def _handle( self, c, m, p, b):
        print b
        

    def close( self ):

        self._channel.stop_consuming()
        print 'done', datetime.datetime.now()

        self._connection.close()

    def run( self ):
        self._channel.basic_consume( self._handle, queue = self._queueID, no_ack = True )
        self._channel.start_consuming()
开发者ID:jebuempak,项目名称:Quant,代码行数:28,代码来源:test_classService.py

示例6: MyServer

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class MyServer(object):
    
    def __init__(self):
        self.conn = BlockingConnection(ConnectionParameters(host="localhost"))
        self.chan = self.conn.channel()
        
    def handler(self, ch, method, props, body):
        print body
        
        nums = len(body)
        sleep(nums)
        
        ch.queue_declare(queue="response", durable=True)
        ch.basic_publish(
            exchange = "",
            routing_key = "response",
            body = body[::-1],
            properties = BasicProperties(
                delivery_mode = 2       
            )
        )
        
        ch.basic_ack(delivery_tag=method.delivery_tag)
        
        
    def start(self):
        self.chan.queue_declare(queue="request", durable=True)
        self.chan.basic_consume(consumer_callback=self.handler, queue="request")
        print "开始监听..."
        self.chan.start_consuming()
开发者ID:djskl,项目名称:Study_RabbitMQ,代码行数:32,代码来源:server.py

示例7: TopicClient

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class TopicClient(object):

    host = config["RABBIT_HOST"]
    port = config["RABBIT_PORT"]
    exchange = config["EXCHANGE"]

    def __init__(self):

        self.conn = BlockingConnection(ConnectionParameters(host=self.host, port=self.port))

        self.channel = self.conn.channel()
        self.channel.exchange_declare(exchange=self.exchange, type="topic")

    def subscribe_to_topic(self, callback, topic):
        result = self.channel.queue_declare(exclusive=True)
        queue_name = result.method.queue

        self.channel.queue_bind(exchange=self.exchange, queue=queue_name, routing_key=topic)
        self.channel.basic_consume(callback, queue=queue_name, no_ack=True)

    def publish_to_topic(self, message, topic):
        self.channel.basic_publish(exchange=self.exchange, routing_key=topic, body=message)

    def run(self):
        print "Start something"
        try:
            self.channel.start_consuming()
        except KeyboardInterrupt:
            print "Closing"
            self.channel.stop_consuming()
            self.conn.close()
开发者ID:tomdottom,项目名称:microservice-client-example,代码行数:33,代码来源:client.py

示例8: main

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
def main():
    connection = BlockingConnection(ConnectionParameters(host='localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='calc', durable=True)
    print ' [*] Waiting for messages. To exit press CTRL+C'

    def callback(ch, method, properties, body):
        print " [x] Persistence {}".format(properties.delivery_mode == 2)
        print " [x] Received: {}".format(body)
        try:
            print " [.] Caclulated: {} = {}".format(body, eval(body))
        except SyntaxError:
            print " [.] Invalid syntax"
        print " [x] Done"
        ch.basic_ack(delivery_tag=method.delivery_tag)

    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(callback,
                          queue='calc')
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        print "[*] Exit"
        return
开发者ID:m-messiah,项目名称:ROT,代码行数:27,代码来源:slave.py

示例9: direct_exchange

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
def direct_exchange():
    connection = BlockingConnection(ConnectionParameters("localhost"))
    channel = connection.channel()

    # connect to exchange and queue
    channel.exchange_declare(exchange="direct_logs", type="direct")

    # create multiple queues to handle each type of severity
    severities = ["critical", "error", "warning", "info", "debug"]
    for severity in severities:
        channel.queue_declare(queue=severity)
        channel.queue_bind(exchange="direct_logs", queue=severity, routing_key=severity)

    # pick a random severity level queue to attach this worker to
    from random import choice

    severities = ["critical", "error", "warning", "info", "debug"]
    severity = choice(severities)
    severity = "info"

    # don't send tasks to this worker until it's ready, keep them in the queue for other workers
    # THIS IS IMPORTANT, otherwise adding more workers won't help anything cause
    # all msgs will already have been sent to the currently 'busy' worker(s)
    channel.basic_qos(prefetch_count=1)

    channel.basic_consume(callback, queue=severity)
    print " [*] Waiting for messages in %s queue. To exit press CTRL+C" % (severity)
    channel.start_consuming()
开发者ID:vegarbg,项目名称:py,代码行数:30,代码来源:worker.py

示例10: MyClient

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class MyClient(object):
    
    def __init__(self):
        self.conn = BlockingConnection(ConnectionParameters(host="localhost"))
        self.chan = self.conn.channel()
    
    def handler(self, ch, method, props, body):
        ch.basic_ack(delivery_tag = method.delivery_tag)
        ch.stop_consuming()
        
    def reverse(self, s):
        self.chan.queue_declare(queue="request", durable=True)
        self.chan.basic_publish(
            exchange="",
            routing_key="request",
            body=s,
            properties = BasicProperties(
                delivery_mode = 2
            )
        )
        
        self.chan.queue_declare(queue="response", durable=True)
        self.chan.basic_consume(
            consumer_callback = self.handler,
            queue = "response"
        )
        self.chan.start_consuming()
开发者ID:djskl,项目名称:Study_RabbitMQ,代码行数:29,代码来源:client.py

示例11: rabbit_connect

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
 def rabbit_connect(self):
     if 'queue_host' in self.config:
         host = self.config['queue_host']
     else:
         host = 'localhost'
     conn = BlockingConnection(ConnectionParameters(host, connection_attempts=3))
     self.rabbit = conn.channel()
     self.rabbit.queue_declare(queue=RABBIT_QUEUE)
开发者ID:nicr9,项目名称:daftpunk,代码行数:10,代码来源:searcher.py

示例12: __init__

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
 def __init__(self, url, context, marshal, unmarshal):
     self._context = context
     self.marshal, self.unmarshal = marshal, unmarshal
     host = match(r"amqp://([\w\d\.]+)", url).group(1)
     connection = BlockingConnection(ConnectionParameters(host))
     self._channel = connection.channel()
     self._channel.exchange_declare(exchange=EXCHANGE, type='topic')
     self._init_docstore()
开发者ID:douglassquirrel,项目名称:alexandra,代码行数:10,代码来源:pubsub.py

示例13: _get_channel

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
def _get_channel():
    global _channel
    assert 'kompaq' in settings.INSTALLED_APPS

    if not _channel:
        connection = BlockingConnection(URLParameters(settings.KOMPAQ_URL))
        _channel = connection.channel()

    return _channel
开发者ID:Siikakala,项目名称:kompassi,代码行数:11,代码来源:utils.py

示例14: __init__

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
class PubSub:
    def __init__(self, url, exchange):
        self.conn = BlockingConnection(URLParameters(url))
        self.exchange = exchange
        self._create_channel_and_exchange()

    def publish(self, topic, fact):
        self._check_channel()
        self.channel.basic_publish(exchange=self.exchange,
                                   routing_key=topic,
                                   body=dumps(fact))

    def subscribe(self, topic):
        self._check_channel()
        queue = self.channel.queue_declare(exclusive=False).method.queue
        self.channel.queue_bind(exchange=self.exchange, queue=queue,
                                routing_key=topic)
        return queue

    def fetch_from_sub(self, topic, queue, timeout, spin=spin):
        self._check_channel()
        result = spin(lambda: self._check_queue(queue), timeout)
        return self._safe_loads(result)

    def consume(self, topic, consumer):
        self._check_channel()
        def rabbit_consumer(channel, method, properties, body):
            consumer(method.routing_key, loads(body))
        queue = self.subscribe(topic)
        self.channel.basic_consume(rabbit_consumer, queue=queue, no_ack=True)
        self.channel.start_consuming()

    def _check_queue(self, queue):
        try:
            return self.channel.basic_get(queue=queue, no_ack=True)[2]
        except AMQPError as e:
            raise PubSubError(e)

    def _safe_loads(self, value):
        if value is None:
            return None
        else:
            return loads(value)

    def _check_channel(self):
        if not self.channel.is_open:
            stderr.write('Channel was closed, reopening')
            self._create_channel_and_exchange()
            if not self.channel.is_open:
                raise CannotReopenChannelError

    def _create_channel_and_exchange(self):
        self.channel = self.conn.channel()
        self.channel.exchange_declare(exchange=self.exchange, type='topic')
开发者ID:jak,项目名称:combo,代码行数:56,代码来源:pubsub.py

示例15: work_queue

# 需要导入模块: from pika import BlockingConnection [as 别名]
# 或者: from pika.BlockingConnection import channel [as 别名]
def work_queue():
    message = ' '.join(sys.argv[1:]) or "Hello World!"
    
    connection = BlockingConnection(ConnectionParameters('localhost'))
    channel = connection.channel()
    queue_name = 'work_queue'
    
    # create a work queue and send a message directly to it, bypassing the exchange
    channel.queue_declare(queue='work_queue', durable=True)
    channel.basic_publish(exchange='', routing_key='work_queue', body=message,  properties=BasicProperties(delivery_mode=2))
    print " [x] Sent '%s'" % (message)
    connection.close()
开发者ID:imclab,项目名称:py,代码行数:14,代码来源:sender.py


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