I am using Django Rest Framework and below is the code of one of the API Endpoints. The code creates generates the PUBLIC and SECRET Values based on Stellar SDK.
def create(self, request):
try:
if 'app_id' not in request.data:
response = {'status': 'FAIL', 'data': 'App ID field not found'}
return Response(response, status=status.HTTP_400_BAD_REQUEST)
if 'customer_id' not in request.data:
response = {'status': 'FAIL', 'data': 'Customer ID field not found'}
return Response(response, status=status.HTTP_400_BAD_REQUEST)
customer_id = request.data['customer_id']
app_id = request.data['app_id']
app = App.objects.get(id=app_id)
# Creating Stellar Account
addr, secret = create_account()
if addr is None and secret is None:
response = {'status': 'FAIL', 'data': 'Could not generate customer Wallet'}
return Response(response, status=status.HTTP_200_OK)
# Make sure we do not add duplicate customers
wallet_count = Wallet.objects.filter(customer_id=customer_id).count()
if wallet_count > 0:
response = {'status': 'FAIL', 'data': 'The customer ID already exist'}
return Response(response, status=status.HTTP_200_OK)
# The customer does not exist, hence create his wallet.
wallet = Wallet(customer_id=customer_id, app=app, address=addr, secret=secret)
wallet.save()
if wallet.pk is None and wallet.pk > 0:
response = {'status': 'OK', 'data': 'success'}
else:
response = {'status': 'FAIL', 'data': 'Messed up'}
except App.DoesNotExist:
response = {'status': 'FAIL', 'data': 'The App ID not found'}
return Response(response, status=status.HTTP_404_NOT_FOUND)
return Response({'status': 'OK', 'data': 'success'}, status=status.HTTP_200_OK)
As you can see there is repetition of codeblock like below:
response = {'status': 'FAIL', 'data': 'The customer ID already exist'}
return Response(response, status=status.HTTP_200_OK)
It'd be nice if I can reduce all this code either by passing to a function or someway once and let it handle based on request
dict.