Package: rctiplus-rabbitmq-python-sdk
IntroductionA library from RCTI+ to handle RabbitMQ tasks (connect, send, receive, etc) in Python.RequirementsPython >=3.7.3Pika ==1.2.0Aio-pika ==6.8.0Requests >=2.25.1Installationpipinstallrctiplus-rabbitmq-python-sdkGetting latest versionpip install rctiplus-rabbitmq-python-sdk --upgradeUsageTo start using this SDK, you may follow given instructions bellow in order.Payload handlerFirst, you need to create a payload class handler that implementMessagePayload. For example, we want to make a class to handle JSON payload:importjsonfromrctiplus_rabbitmq_python_sdkimportMessagePayloadclassJSONPayload(MessagePayload):"""Example class to handle JSON payload"""def__init__(self,firstname:str,lastname:str)->None:self.firstname=firstnameself.lastname=lastnamedef__str__(self)->str:"""Convert JSON to string payload messageReturns:str: String payload message"""returnjson.dumps({'firstname':self.firstname,'lastname':self.lastname})@classmethoddeffrom_str(cls,message:str)->'JSONPayload':"""Generate data from JSON string payload messageReturns:JSONPayload: Generated data"""payload=json.loads(message)returncls(firstname=payload['firstname'],lastname=payload['lastname'])MessagePayloadclass from the SDK's core has this functions that require to implemented:classMessagePayload:"""Python RabbitMQ message payload"""@classmethoddeffrom_str(cls,message:str)->'MessagePayload':"""Generate data from specified string payload message formatRaises:NotImplementedError: Raise an error if not implemented"""raiseNotImplementedError()def__str__(self)->str:"""Convert specified data format to string payload messageRaises:NotImplementedError: Raise an error if not implementedReturns:str: String payload message"""raiseNotImplementedError()Connect to RabbitMQMaking connection to RabbitMQ server can be done by doing this simple way:fromrctiplus_rabbitmq_python_sdkimportRabbitMQconn=RabbitMQ()conn.connect(host='localhost',port=5672,username='guest',password='guest')Sending messageAfter you have payload class handler & connected to the RabbitMQ server, now you can try to send a messsage to queue channel. For example, we will send JSON payload message totestqueue:payload=JSONPayload('John','Doe')print('payload:',payload)conn.send('test',payload)Receiving messageGreat. Now, in our consumer app, we want to listen & receive that message, and then doing some stuff:defcallback(ch,method,properties,body):print("[x] Received%r"%body)data=JSONPayload.from_str(body)print(f'data: firstname={data.firstname}, lastname={data.lastname}')conn.receive('test',callback)Forcallbackfunction, according toPikas standart library, you need to pass 4 argumentsch,method,propertiesandbodyto catch all needed values from incomming message.Putting it all togetherHere is the complete example from the code above:Complete example of sender or producer app:importjsonfromrctiplus_rabbitmq_python_sdkimportRabbitMQ,MessagePayload# Create payload class handler that implement `MessagePayload`classJSONPayload(MessagePayload):"""Example class to handle JSON payload"""def__init__(self,firstname:str,lastname:str)->None:self.firstname=firstnameself.lastname=lastnamedef__str__(self)->str:"""Convert JSON to string payload messageReturns:str: String payload message"""returnjson.dumps({'firstname':self.firstname,'lastname':self.lastname})@classmethoddeffrom_str(cls,message:str)->'JSONPayload':"""Generate data from JSON string payload messageReturns:JSONPayload: Generated data"""payload=json.loads(message)returncls(firstname=payload['firstname'],lastname=payload['lastname'])# Connect to RabbitMQconn=RabbitMQ()conn.connect(host='localhost',port=5672,username='guest',password='guest')# Send payload to queuepayload=JSONPayload('John','Doe')print('payload:',payload)conn.send('test',payload)Complete example of consumer or receiver app:importjsonfromrctiplus_rabbitmq_python_sdkimportRabbitMQ,MessagePayload# Create payload class handler that implement `MessagePayload`classJSONPayload(MessagePayload):"""Example class to handle JSON payload"""def__init__(self,firstname:str,lastname:str)->None:self.firstname=firstnameself.lastname=lastnamedef__str__(self)->str:"""Convert JSON to string payload messageReturns:str: String payload message"""returnjson.dumps({'firstname':self.firstname,'lastname':self.lastname})@classmethoddeffrom_str(cls,message:str)->'JSONPayload':"""Generate data from JSON string payload messageReturns:JSONPayload: Generated data"""payload=json.loads(message)returncls(firstname=payload['firstname'],lastname=payload['lastname'])# Connect to RabbitMQconn=RabbitMQ()conn.connect(host='localhost',port=5672,username='guest',password='guest')# Create a callback to be executed immadiately after recieved a messagedefcallback(ch,method,properties,body):print("[x] Received%r"%body)# Generate data from string payload messagedata=JSONPayload.from_str(body)print(f'data: firstname={data.firstname}, lastname={data.lastname}')# Receive & listen messages from queue channelconn.receive('test',callback)AsynchronousThis SDK also support asynchronous process. To use this feature, useAIORabbitMQinstead ofRabbitMQ. All methods provided inAIORabbitMQare treated asasyncfunction. So, when you calling the methods, you need toawaitthem.Async connect to RabbitMQfromrctiplus_rabbitmq_python_sdkimportAIORabbitMQconn=AIORabbitMQ(loop)awaitconn.connect(host='localhost',port=5672,username='guest',password='guest')loopis an asynchronous event loop, example:asyncio.get_event_loop()Async sending messagepayload=JSONPayload('John','Doe')print('payload:',payload)awaitconn.send('test',payload)Async receiving messageasyncdefcallback(message):body=message.bodyprint("[x] Received%r"%body)data=JSONPayload.from_str(body)print(f'data: firstname={data.firstname}, lastname={data.lastname}')awaitconn.receive('test',callback)In asynchronous process, you just need pass 1 argument oncallbackfunction. This argument is a representation ofaio_pika.IncomingMessageto catch all needed values from incomming message.Complete example of asynchronous processHere is the complete example of asynchronous process above:Complete example of asynchronous sender or producer app:importjsonimportasynciofromrctiplus_rabbitmq_python_sdkimportAIORabbitMQ,MessagePayload# Create payload class handler that implement `MessagePayload`classJSONPayload(MessagePayload):"""Example class to handle JSON payload"""def__init__(self,firstname:str,lastname:str)->None:self.firstname=firstnameself.lastname=lastnamedef__str__(self)->str:"""Convert JSON to string payload messageReturns:str: String payload message"""returnjson.dumps({'firstname':self.firstname,'lastname':self.lastname})@classmethoddeffrom_str(cls,message:str)->'JSONPayload':"""Generate data from JSON string payload messageReturns:JSONPayload: Generated data"""payload=json.loads(message)returncls(firstname=payload['firstname'],lastname=payload['lastname'])# Main functionasyncdefmain(loop):# Connect to RabbitMQconn=AIORabbitMQ(loop)awaitconn.connect(host='localhost',port=5672,username='guest',password='guest')asyncwithconn.connection:# Send payload to queuepayload=JSONPayload('John','Doe')print('payload:',payload)awaitconn.send('test',payload)# Event looploop=asyncio.get_event_loop()loop.run_until_complete(main(loop))loop.close()Complete example of asynchronous consumer or receiver app:importjsonimportasynciofromrctiplus_rabbitmq_python_sdkimportAIORabbitMQ,MessagePayload# Create payload class handler that implement `MessagePayload`classJSONPayload(MessagePayload):"""Example class to handle JSON payload"""def__init__(self,firstname:str,lastname:str)->None:self.firstname=firstnameself.lastname=lastnamedef__str__(self)->str:"""Convert JSON to string payload messageReturns:str: String payload message"""returnjson.dumps({'firstname':self.firstname,'lastname':self.lastname})@classmethoddeffrom_str(cls,message:str)->'JSONPayload':"""Generate data from JSON string payload messageReturns:JSONPayload: Generated data"""payload=json.loads(message)returncls(firstname=payload['firstname'],lastname=payload['lastname'])# Main functionasyncdefmain(loop):# Connect to RabbitMQconn=AIORabbitMQ(loop)awaitconn.connect(host='localhost',port=5672,username='guest',password='guest')# Create a callback to be executed immadiately after recieved a messageasyncdefcallback(message):body=message.bodyprint("[x] Received%r"%body)# Generate data from string payload messagedata=JSONPayload.from_str(body)print(f'data: firstname={data.firstname}, lastname={data.lastname}')# Receive & listen messages from queue channelawaitconn.receive('test',callback)returnconn# Event looploop=asyncio.get_event_loop()connection=loop.run_until_complete(main(loop))try:loop.run_forever()finally:loop.run_until_complete(connection.disconnect())LicenseGNU General Public License v3