Package: bgtasks
bgtasksbgtasks is python library for dealing with data exchange between
micro services using rabbitmq protocol. Moreover, you can use it as trigger for events which belongs to another services.InstallationUse the package managerpipto install bgtasks.pipinstallbgtasksConfigurationsettings.pyAMQP={'USERNAME':'guest','PASSWORD':'guest','VHOST':'/','HOST':'localhost','PORT':5672,'RPC_SLEEP_TIME':0.005,'RPC_TIMEOUT':5,}Default values'RPC_TIMEOUT': 60
'RPC_SLEEP_TIME': 0.05,UsageCreating bgtask view for handle actions throughrouteapp1 tasks.pyfrombgtasksimportrpc_tasksfrombgtasksimportResponse@rpc_tasks('message')defhandle(data):print(data)returnResponse('I received your message%s'%data)To get responsefrombgtasksimportRPCClientrpc_client=RPCClient()try:response=rpc_client.call('message','Hi')print(response)exceptTimeoutError:print('Service is not responding')In order to avoid conflicts between remote procedure calls you should pass parametersexplicitly with keywordsTo run rpc task run command belowpythonmanage.pytasksRestFrameworkservice1Modelmodels.pyfromdjango.dbimportmodelsclassCategory(models.Model):name=models.CharField(max_length=255)In this case youraddshould receive arguments' list with explicit variable nameidsTaskstasks.pyfrombgtasksimportrpc_tasksfrombgtasksimportResponsefrombgtasksimportserializer_classfromtestapp.modelsimportCategoryfromrest_frameworkimportserializersclassCategorySerializer(serializers.ModelSerializer):classMeta:model=Categoryfields=('id','name')@rpc_tasks('add')@serializer_class(CategorySerializer,many=True)defhandle(serializer):serializer.save()returnResponse(serializer.data)@rpc_tasks('get')@serializer_class()defhandle(serializer):queryset=Category.objects.filter(id__in=serializer.validated_data['ids'])serializer=CategorySerializer(queryset,many=True)returnResponse(serializer.data)service2app1 models.pyfromdjango.dbimportmodelsfrombgtasks.modelsimportRemoteFieldclassProduct(models.Model):name=models.CharField(max_length=255)category=RemoteField()# in our case, it is in another service idRemoteFieldfromrest_frameworkimportserializersfrombgtasks.rest_framework.fieldsimportRemoteFieldfromapp1.modelsimportProductclassProductSerializer(serializers.ModelSerializer):category=RemoteField(route='get')classMeta:model=Productfields=('id','name','category',)FormatAnd make sure that returned response should be formed as below format.{'status':'success/fail','data':[{'id':1,# 'data'},{'id':2,# data}]}Handling list serializerIn order to avoid from sending many rpc requests at first level of serializer we added RPCSerializerMixinfrombgtasksimportRemoteFieldfrombgtasks.rest_framework.serilaizersimportRPCSerializerMixinfromrest_frameworkimportserializersfromapp1.modelsimportProductclassProductListSerializer(RPCSerializerMixin,serializers.ModelSerializer):category=RemoteField(route='get')classMeta:model=Productfields='__all__'users=Product.objects.all()serializer=ProductListSerializer(users,many=True)print(serializer.data)It will send torouteonerequest with gathered pks in body as[1,2,3,4,5], after which will be iterated to merge current serializer data
which maps toidfield in rpc responseOutput[{'id':1,'name':'IPhone','category':{'id':5,'name':'Phone',}},{'id':2,'name':'LG Smart Tv','category':{'id':3,'name':'TV',}},]Merge methodsTo handlemany=Truein serializer we introduceRPCSerializerMixinwhich uses merge functions.
You can import them as below, and to understand can look to function profile.frombgtasks.utils.mergeimportmerge,merge_dict,merge_objTestingAddENVIRONMENT = 'test'on settings.py in order to imitate response from
another serviceimportjsonfromdjango.testimportTestCasefromdjango.testimportClientfrombgtasksimportrpc_tasksfrombgtasksimportRPCClientfrombgtasksimportSUCCESSfrombgtasks.amqpimportregister_tasks@rpc_tasks('user.add')defadd_user(data):return1classRPCTestCase(TestCase):defsetUp(self):register_tasks()# If you want to run your tasks to test them out, not only rpc tasks which are registered inside of your test filedeftest_add_user(self):data={'username':'john','password':'smith'}c=Client()response=c.post('/user/add/',data)data=json.loads(response.content)self.assertEqual(response.status_code,201)self.assertEqual(data['user_id'],1)deftest_your_tasks(self):data=RPCClient().call('mytasks',{})self.assertEqual(data['status'],SUCCESS)ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.How to deployCreate config file in home directory~/.pypirc[distutils] 
index-servers=pypi
[pypi] 
repository = https://upload.pypi.org/legacy/ 
username = myrubapaAfter run command for build and deploypython3setup.pysdistbdist_wheel
python3-mtwineuploaddist/*for more detail readpackaging-projectsLicenseMIT