I have a method in my API that handles the sync operations with the company’s ERP. This method is called once every 30 minutes by a script I made to ensure that everything will be always up date. However, if someone wants, they also can make a request to the endpoint by themselves, but they also need to be informed if the operation is currently processing or not
So, my solution is: I keep a flag on the database and set it to true
when the transaction ongoing and false
when it ends, so my application will check it and proceed/stop based on this condition
There’s just one problem: as I’m keeping everything in a single transaction, the flag is actually useless since only inside the single transaction it will be set to true
. I thought about updating the flag before starting the transaction and reverting it whenever an error happens, but I can’t ensure the reversal process will happen 100% the times (so there’s a possibility to lock the operation)
My code is the following one, if anyone needs it for reference:
@api_view(['POST'])
def syncErpItems(request):
try:
with transaction.atomic():
job = Jobs.objects.get(name='items')
if job.updating:
return Response({'message': 'Sync already ongoing'})
job.updating = True
job.save()
updateItems()
job.updating = False
job.last_execution = timezone.now()
job.save()
return Response({'message': 'Success'})
except Exception as e:
return Response({'message': 'Error on sync: ' + str(e)})
Some things to keep in mind:
- It is not a possibility to let the lock happen and manually fix it later given other circumstances
- The sync operation takes like 30/40 seconds, there are lots of content coming from the ERP