-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.py
56 lines (49 loc) · 1.66 KB
/
session.py
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
47
48
49
50
51
52
53
54
55
56
from __future__ import annotations
import pika
from pika.adapters.blocking_connection import BlockingConnection
from os import environ
class MQSession:
"""
Class that implement AMQP protocol comunication.
"""
def __init__(self, host, port, username, password, virtual_host):
"""
Class constructor.
"""
self.host = host
self.port = port
self.username = username
self.password = password
self.virtual_host = virtual_host
def __enter__(self) -> BlockingConnection:
"""
Create a connection at RabbitMQ.
:returns: Connection session
"""
credentials = pika.PlainCredentials(self.username, self.password)
params = pika.ConnectionParameters(
host=self.host,
port=self.port,
credentials=credentials,
virtual_host=self.virtual_host)
# pylint: disable=attribute-defined-outside-init
self.connection = pika.BlockingConnection(params)
return self.connection
def __exit__(self, exc_type, exc_value, exc_tb):
"""
Stop the RabbitMMQ connection.
"""
self.connection.close()
@classmethod
def default_session(cls) -> MQSession:
"""
A default session for RabbitMQ protocol, with all connection data.
:returns: MQSession instance
"""
return MQSession(
host=environ.get("MQ_HOST", "rabbitmq"),
port=environ.get("MQ_PORT", 5672),
username=environ.get("MQ_USER", "brock"),
password=environ.get("MQ_PASS", "onix"),
virtual_host=environ.get("MQ_PORT", "pewtergym"),
)