Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import logging
import os
import pika
logger = logging.getLogger(__name__)
logging.getLogger("pika").setLevel(logging.WARNING)
BROKER_ADDRESS = os.getenv('BROKER_ADDRESS') or 'localhost'
BROKER_USER = os.getenv('BROKER_USER') or None
BROKER_PASSWORD = os.getenv('BROKER_PASSWORD') or None
def test_connection():
try:
# Create a connection to the broker
connection = get_blocking_connection()
# Declare a channel and a queue
channel = connection.channel()
# Close the connection
connection.close()
except Exception as e:
logger.error(f"Failed to connect to broker; message: {e}")
raise
def get_blocking_connection():
if BROKER_USER is not None:
credentials = pika.PlainCredentials(username=BROKER_USER, password=BROKER_PASSWORD)
parameters = pika.ConnectionParameters(host=BROKER_ADDRESS, credentials=credentials)
return pika.BlockingConnection(parameters)
else:
parameters = pika.ConnectionParameters(host=BROKER_ADDRESS)
return pika.BlockingConnection(parameters)
def get_select_connection(on_open_callback):
if BROKER_USER is not None:
credentials = pika.PlainCredentials(username=BROKER_USER, password=BROKER_PASSWORD)
parameters = pika.ConnectionParameters(host=BROKER_ADDRESS, credentials=credentials)
return pika.SelectConnection(parameters=parameters, on_open_callback=on_open_callback)
else:
parameters = pika.ConnectionParameters(host=BROKER_ADDRESS)
return pika.SelectConnection(parameters=parameters, on_open_callback=on_open_callback)