def _amqp_conn_params(self): vhost = self.def_amqp.virtual_host if 'virtual_host' in self.def_amqp else self.def_amqp.vhost if 'credentials' in self.def_amqp: username = self.def_amqp.credentials.username password = self.def_amqp.credentials.password else: username = self.def_amqp.username password = self.def_amqp.password params = ConnectionParameters(self.def_amqp.host, int(self.def_amqp.port), vhost, PlainCredentials(username, password), frame_max=int(self.def_amqp.frame_max)) # heartbeat is an integer but ConnectionParameter.__init__ insists it # be a boolean. params.heartbeat = float(self.def_amqp.heartbeat) return params
def main(): queue_name = "puccini_clean" host = 'localhost' conn = BlockingConnection(ConnectionParameters('localhost')) channel = conn.channel() channel.queue_declare(queue_name) channel.basic_publish(exchange='', routing_key=queue_name, body=json.dumps({'clean': True})) channel.close() conn.close()
def main(): queue_name = "grq_clean" host = 'localhost' conn = BlockingConnection(ConnectionParameters('localhost')) channel = conn.channel() channel.queue_declare(queue_name, durable=True) channel.basic_publish(exchange='', routing_key=queue_name, body=json.dumps({'clean': True}), properties=BasicProperties(delivery_mode=2)) channel.close() conn.close()
def connection_parameters(config): args = { 'host': config.get('host', ConnectionParameters._DEFAULT), 'port': config.get('port', ConnectionParameters._DEFAULT), 'virtual_host': config.get('virtual_host', ConnectionParameters._DEFAULT), } if 'username' in config: args['credentials'] = pika.PlainCredentials( config.get('username', Parameters.DEFAULT_USERNAME), config.get('password', Parameters.DEFAULT_PASSWORD)) return ConnectionParameters(**args)
def _amqp_conn_params(self): vhost = self.def_amqp.virtual_host if 'virtual_host' in self.def_amqp else self.def_amqp.vhost if 'credentials' in self.def_amqp: username = self.def_amqp.credentials.username password = self.def_amqp.credentials.password else: username = self.def_amqp.username password = self.def_amqp.password params = ConnectionParameters(self.def_amqp.host, int(self.def_amqp.port), vhost, PlainCredentials(username, password), frame_max=int(self.def_amqp.frame_max)) # heartbeat is an integer but ConnectionParameter.__init__ insists it # be a boolean. params.heartbeat = float(self.def_amqp.heartbeat) return params
def make_node(connection_params=None, name=None, timeout=None): """ Blocking construction and connection of node. @param connection_params AMQP connection parameters. By default, uses CFG.server.amqp (most common use). """ log.debug("In make_node") node = NodeB() connection_params = connection_params or CFG.server.amqp credentials = PlainCredentials(connection_params["username"], connection_params["password"]) conn_parameters = ConnectionParameters(host=connection_params["host"], virtual_host=connection_params["vhost"], port=connection_params["port"], credentials=credentials) connection = PyonSelectConnection(conn_parameters , node.on_connection_open) ioloop_process = gevent.spawn(ioloop, connection, name=name) #ioloop_process = gevent.spawn(connection.ioloop.start) node.ready.wait(timeout=timeout) return node, ioloop_process
def startService(self): params = {} if self.settings.get("username", None, section='amqp') \ and self.settings.get("pass", None, section='amqp'): params['credentials'] = pika_credentials.PlainCredentials( self.settings.get("username", None, section='amqp'), self.settings.get("pass", None, section='amqp')) if self.settings.getdict("params", dict(), section='amqp'): params.update( self.settings.getdict("params", dict(), section='amqp')) if self.settings.get("amqp_vhost", '/'): params.update({ 'virtual_host': self.settings.get("vhost", '/', section='amqp') }) parameters = ConnectionParameters(**params) self._client = protocol.ClientCreator( reactor, twisted_connection.TwistedProtocolConnection, parameters) self.do_connect()
def make_node(connection_params=None, name=None, timeout=None): """ Blocking construction and connection of node. @param connection_params AMQP connection parameters. By default, uses CFG.server.amqp (most common use). @return tuple of node and ioloop greenlet """ log.debug("In make_node") node = NodeB() connection_params = connection_params or CFG.get_safe("server.amqp") credentials = PlainCredentials(connection_params["username"], connection_params["password"]) conn_parameters = ConnectionParameters( host=connection_params["host"], virtual_host=connection_params["vhost"], port=connection_params["port"], credentials=credentials) connection = PyonSelectConnection(conn_parameters, node.on_connection_open) ioloop_gl = gevent.spawn(ioloop, connection, name=name) ioloop_gl._glname = "ScionCC AMQP ioloop" node.ready.wait(timeout=timeout) return node, ioloop_gl
# Setup empty ssl options ssl_options = {} # Uncomment this to test client certs, change to your cert paths # Uses certs as generated from http://www.rabbitmq.com/ssl.html ssl_options = { "ca_certs": "/etc/rabbitmq/new/server/chain.pem", "certfile": "/etc/rabbitmq/new/client/cert.pem", "keyfile": "/etc/rabbitmq/new/client/key.pem", "cert_reqs": CERT_REQUIRED } # Connect to RabbitMQ host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1' parameters = ConnectionParameters(host, 5671, ssl=True, ssl_options=ssl_options) 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 conneciton is closed connection.ioloop.start()
def on_queue_declared(frame): print "demo_receive: Queue Declared" channel.basic_consume(handle_delivery, queue='test') def handle_delivery(channel, method_frame, header_frame, body): print "Basic.Deliver %s delivery-tag %i: %s" %\ (header_frame.content_type, method_frame.delivery_tag, body) channel.basic_ack(delivery_tag=method_frame.delivery_tag) if __name__ == '__main__': # 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 conneciton is closed connection.ioloop.start()
env=os.environ) try: sts = pop.wait() #wait for child to terminate and get status except Exception, e: print str(e) status = pop.returncode #print "returncode is:",status stdOut = pop.stdout.read() stdErr = pop.stderr.read() for line in stdOut.split('\n'): if line.startswith("error_queue"): COUNT = int(line.split()[1]) break print "Total number of messages in error_queue:", COUNT if COUNT == 0: sys.exit() # Connect to RabbitMQ host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1' CONNECTION = BlockingConnection(ConnectionParameters(host)) # Open the channel channel = CONNECTION.channel() # loop for method_frame, properties, body in channel.consume('error_queue'): if handle_delivery(channel, method_frame, body): break channel.stop_consuming() channel.close() CONNECTION.close()
import sys from pika import BlockingConnection from pika.credentials import PlainCredentials from pika.connection import ConnectionParameters if len(sys.argv) > 1: rkey = sys.argv[1] or "error" msg = " ".join(sys.argv[2:]) or "shit happen!" else: rkey = "error" msg = "shit happen!" connection = BlockingConnection(parameters=ConnectionParameters( host="localhost", credentials=PlainCredentials(username="******", password="******"), )) ch = connection.channel() exchange = ch.exchange_declare(exchange="topic_log", exchange_type="topic") ch.basic_publish(exchange="topic_log", routing_key=rkey, body=msg) connection.close()
self.lc.stop() d = self.channel.queue_delete(queue=self.queue_name) d.addCallbacks(self.stopped_consuming, twisted_log.err) def stopped_consuming(self, _): pika_log.info("demo_twisted: Consuming stopped, queue deleted") if __name__ == '__main__': if len(sys.argv) != 2: print >> sys.stderr, ("usage: %s [p|t] (use Pika or Twisted " "for connecting" % sys.argv[0]) sys.exit(1) handler = TwistedHandler() parameters = ConnectionParameters() pika_log.setup(color=True) if sys.argv[1] == 'p': TwistedConnection(parameters, handler.on_connected) elif sys.argv[1] == 't': cc = protocol.ClientCreator(reactor, TwistedProtocolConnection, parameters) d = cc.connectTCP('localhost', 5672) d.addCallback(lambda protocol: protocol.ready) d.addCallback(handler.on_connected) d.addErrback(twisted_log.err) else: print >> sys.stderr, ("usage: %s [p|t] (use Pika or Twisted " "for connecting" % sys.argv[0]) sys.exit(1)
PORT = int(environ.get('RABBITMQ_PORT', 5672)) PLATFORM = uname()[0].lower() # Import Warnings import warnings # Validate that we can connect to RabbitMQ import socket socket.setdefaulttimeout(1) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) try: sock.connect((HOST, PORT)) sock.close() except socket.error: warnings.warn("RabbitMQ is not running at %s:%i" % (HOST, PORT)) from nose import SkipTest raise SkipTest("RabbitMQ is not running at %s:%i" % (HOST, PORT)) # Ignore the pika generated warnings warnings.simplefilter('ignore', UserWarning) # Set our connection parameters to be used by our tests from pika.connection import ConnectionParameters PARAMETERS = ConnectionParameters(HOST, PORT) if __name__ == '__main__': print "Platform: %s" % PLATFORM print "Python Version: %s" % PYTHON_VERSION print "RabbitMQ Broker: %s:%i" % (HOST, PORT)
def open(self) -> None: self._connection = pika.BlockingConnection(ConnectionParameters(HOST))
def test_address_1(self): p = ConnectionParameters(host="foobar", port=1234) addr1 = AMQPAddress(p) assert addr1.unparse(routing_key='123') == "amqp://*****:*****@foobar:1234/%2f?routing_key=123" assert AMQPAddress(addr1.get_parameters()).unparse() == 'amqp://*****:*****@foobar:1234/%2f'
def __init__(self): self._connection = BlockingConnection(ConnectionParameters(HOST))
""" Example of the use of basic_get. NOT RECOMMENDED for fast consuming - use basic_consume instead if at all possible! """ import sys import time from pika.adapters import BlockingConnection from pika.connection import ConnectionParameters if __name__ == '__main__': # Connect to RabbitMQ host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1' connection = BlockingConnection(ConnectionParameters(host)) # Open the channel channel = connection.channel() # Declare the queue channel.queue_declare(queue="test", durable=True, exclusive=False, auto_delete=False) # Initialize our timers and loop until external influence stops us while connection.is_open: # Call basic get which returns the 3 frame types method, header, body = channel.basic_get(queue="test")
def __init__(self): self._connection = pika.BlockingConnection( ConnectionParameters(host=HOST))