Skip to content
This repository has been archived by the owner on Oct 18, 2024. It is now read-only.

Commit

Permalink
Merge pull request #65 from EvanVallet/main
Browse files Browse the repository at this point in the history
nats-debug
  • Loading branch information
EvanVallet authored Jun 26, 2024
2 parents ba09982 + bb12f17 commit 7b66712
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 30 deletions.
22 changes: 19 additions & 3 deletions Django_api/airline/api_common/to_nats.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
# nats_utils.py
import asyncio
from nats.aio.client import Client as NATS
import time

async def request_message(subject, message, servers, timeout=1):
async def request_message(subject, message, servers, timeout=0.5):
nc = NATS()
await nc.connect(servers)
await nc.connect(servers,user="user",password="password")

try:
response = await nc.request(subject, message.encode(), timeout=timeout)
response = await nc.request(subject, message.encode())
response = response.data.decode()
await nc.publish("banque.validation", response.encode())
return response
except Exception :
return None
finally:
await nc.drain()
await nc.close()

async def post_message(subject, message, servers, timeout=5):
nc = NATS()
await nc.connect(servers,user="user",password="password")

try:
response = await nc.publish(subject, message.encode(), timeout=timeout)
return response.data.decode()
except Exception :
return None
Expand Down
43 changes: 28 additions & 15 deletions Django_api/airline/api_common/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
from .serializers import *
import asyncio
import nats
from .to_nats import *
from .to_nats import *
import os
import time


class ObtainAuthToken(APIView):
Expand Down Expand Up @@ -225,20 +226,29 @@ def destroy(self, request, *args, **kwargs):
return Response(status=status.HTTP_204_NO_CONTENT)

# new-2
async def vol_delete():
global nc
def vol_delete():
env = os.getenv('DJANGO_ENVIRONMENT', 'development')
user = os.getenv('NATS_USER', '')
password = os.getenv('NATS_PASSWORD', '')
if env == 'development':
nc = await nats.connect("nats://localhost:4222")
else:
nc = await nats.connect("nats://nats:4222",user=user,password=password)
try:
flidht_delete = f"{Flight.objects.get(id=self.kwargs.get('pk'))}"
await nc.publish(f"vol.delete",flidht_delete)
except Exception as e:
print(e)
server="nats://localhost:4222"
post_message("vol.delete",f"{Flight.objects.get(id=self.kwargs.get('pk'))}",server)


#class ConfirmBookingView(APIView):
# permission_classes = [IsAdminUser]
#
# def post(self, request, *args, **kwargs):
# booking_id = request.data.get('booking_id')
# try:
# booking = Booking.objects.get(id=booking_id)
# if booking.status == 'pending':
# booking.status = 'confirmed'
# booking.save()
# return Response({'status': 'Booking confirmed'}, status=status.HTTP_200_OK)
# else:
# return Response({'error': 'Booking is not in a pending state'}, status=status.HTTP_400_BAD_REQUEST)
# except Booking.DoesNotExist:
# return Response({'error': 'Booking not found'}, status=status.HTTP_404_NOT_FOUND)

class AddAirportView(generics.CreateAPIView):
queryset = Airport.objects.all()
Expand Down Expand Up @@ -345,9 +355,12 @@ def post(self, request, *args, **kwargs):
subject="banque.validation"
message = f"{client_id}:{price_seat}"
# Simulate payment process. In a real scenario, you would integrate with a payment gateway.
#data=asyncio.run(request_message(subject,message,server,price_seat))
#data.split(",")
payment_successful = True #data[0] # Replace with True for testing
retour_nats=asyncio.run(request_message(subject,message,server))
time.sleep(3)

payment_successful = retour_nats # Replace with True for testing



if payment_successful:
booking.status = 'confirmed'
Expand Down
28 changes: 16 additions & 12 deletions NATS/banque/banque.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,36 +41,39 @@ async def handle_payment_request(msg):
subject = msg.subject
reply = msg.reply
data = msg.data.decode()
parts = subject.split('.')
client = parts[2]
montant = float(data)
parts = data.split(':')
client = parts[0]

print(f"Requête de paiement reçue : client={client}, montant={montant}")



'''
if client in clients:
if clients[client] >= montant:
print(f"Validation de paiement reçue : autorize={autorize}")
if autorize:
print(f"Paiement de {montant} à {client} autorisé.")
clients[client] -= montant
response_msg = f"True,Payer,Paiement autorisé. Nouveau solde de {client}: {clients[client]}"
response_msg = True
save_clients()
else:
print("Paiement refusé.")
response_msg = "False,Failed,Paiement refusé par l'autorisation."
response_msg = False
else:
print("Paiement refusé, solde insuffisant.")
response_msg = "False,Failed,Paiement refusé, solde insuffisant."
response_msg = False
else:
print("Client inconnu.")
response_msg = "False,Failed,Client inconnu."
response_msg = False
'''
#response_msg = "True"
#await nc.publish("banque.validation", response_msg.encode())

await nc.publish(reply, response_msg.encode())

except Exception as e:
print(f"Erreur: {str(e)}")
await nc.publish(reply, f"Erreur: {str(e)}".encode())
rep=f"Erreur: {str(e)}"
await nc.publish(reply, rep.encode())

async def handle_account_request(msg):
subject = msg.subject
Expand Down Expand Up @@ -147,11 +150,12 @@ async def main():
await nc.subscribe("banque.*.compte", cb=handle_account_request)
await nc.subscribe("banque.creation", cb=handle_create_account_request)
await nc.subscribe("banque.list_accounts", cb=handle_list_accounts_request)
await nc.subscribe("banque.validation.*", cb=handle_payment_request)
await nc.subscribe("banque.validation", cb=handle_payment_request)
await nc.subscribe("banque.*.rembousement", cb=handle_remboursement_request)

while True:
await asyncio.sleep(1)

except asyncio.CancelledError:
pass
finally:
Expand Down

0 comments on commit 7b66712

Please sign in to comment.