Advertisement
bbcqx

Untitled

Aug 11th, 2023
1,568
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. class RabbitmqConnectionFactory:
  2.     # ...
  3.  
  4.     def __enter__(self):
  5.         credentials = pika.credentials.PlainCredentials(
  6.             self.username, self.password
  7.         )
  8.         self.connection = pika.BlockingConnection(
  9.             pika.ConnectionParameters(self.host, self.port, "/", credentials)
  10.         )
  11.         self._make_new_channel()
  12.         return self
  13.  
  14.     def __exit__(self, exc_type, exc_value, traceback):
  15.         self._close_channel()
  16.         self._close_connection()
  17.  
  18.     def _make_new_channel(self):
  19.         if self.connection and self.connection.is_open:
  20.             self.channel = self.connection.channel()
  21.  
  22.     def _close_channel(self):
  23.         if self.channel and not self.channel.is_closed:
  24.             self.channel.close()
  25.  
  26.     def _close_connection(self):
  27.         if self.connection and not self.connection.is_closed:
  28.             self.connection.close()
  29.  
  30.     def _get_channel(self):
  31.         if (not self.connection or self.connection.is_closed or
  32.             not self.channel or self.channel.is_closed):
  33.             self.__exit__(None, None, None)
  34.             self.__enter__()
  35.         return self.channel
  36.  
  37.     # ... rest of the class
  38.    
  39.    
  40.     # USE like this ONLY:
  41.  
  42.     with RabbitmqConnectionFactory(...) as rq:
  43.         rq.declare_queue(...)
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement