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

Commit

Permalink
to_nats valid
Browse files Browse the repository at this point in the history
  • Loading branch information
EvanVallet committed Jun 26, 2024
1 parent bb12f17 commit 5115ffa
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 37 deletions.
1 change: 1 addition & 0 deletions Django_Frontend/monprojet/monapp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
path('flights/', views.view_flights, name='flights'),
path('book-flight/<int:flight_id>/', views.book_flight, name='book_flight'),
path('success/', views.success, name='success'),
path('error/', views.success, name='error'),
path('bookings/', views.view_bookings, name='view_bookings'),
path('transactions/', views.transactions_view, name='transactions_view'),
path('payment/<int:booking_id>/', views.payment, name='payment'),
Expand Down
14 changes: 13 additions & 1 deletion Django_Frontend/monprojet/monapp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ def success(request):
"""
return render(request, 'monapp/success.html')

def error(request):
"""
Display the error page.
This view is triggered after a wrong operation, such as form submission. It renders a generic error message to inform the user that their action was completed successfully.
:param request: HttpRequest object
:return: HttpResponse object rendering the error page.
"""
return render(request, 'monapp/error.html')


def home(request):
"""
Display the home page.
Expand Down Expand Up @@ -347,7 +359,7 @@ def payment(request, booking_id):
return redirect('success')
else:
# Handle payment failure
return render(request, 'monapp/payment.html', {'form': form, 'booking': booking, 'error': 'Payment failed. Please try again.'})
return redirect('error')
else:
form = PaymentForm(initial={'booking_id': booking_id})
return render(request, 'monapp/payment.html', {'form': form, 'booking': booking})
Expand Down
5 changes: 2 additions & 3 deletions Django_api/airline/api_common/to_nats.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async def request_message(subject, message, servers, timeout=0.5):
try:
response = await nc.request(subject, message.encode())
response = response.data.decode()
await nc.publish("banque.validation", response.encode())
#await nc.publish("banque.validation", response.encode())
return response
except Exception :
return None
Expand All @@ -23,8 +23,7 @@ async def post_message(subject, message, servers, timeout=5):
await nc.connect(servers,user="user",password="password")

try:
response = await nc.publish(subject, message.encode(), timeout=timeout)
return response.data.decode()
await nc.publish(subject, message.encode(), timeout=timeout)
except Exception :
return None
finally:
Expand Down
28 changes: 5 additions & 23 deletions Django_api/airline/api_common/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from .to_nats import *
import os
import time

import random

class ObtainAuthToken(APIView):
permission_classes = (AllowAny,)
Expand All @@ -28,31 +28,13 @@ def post(self, request, *args, **kwargs):
if user:
user_id_bank = user.id
token, created = Token.objects.get_or_create(user=user)
asyncio.run(self.banque_account_create(user_id_bank))
asyncio.run(post_message("banque.creation",f"{user_id_bank}:{random.randint(200:800)}",server="nats://nats:4222"))
return Response({'token': token.key})
else:
return Response({'error': 'Invalid Credentials'}, status=status.HTTP_400_BAD_REQUEST)

async def banque_account_create(self, user_id_bank):
global nc
env = os.getenv('DJANGO_ENVIRONMENT', 'development')
user = os.getenv('NATS_USER', 'user')
password = os.getenv('NATS_PASSWORD', 'password')
if env == 'development':
nc = await nats.connect("nats://localhost:4222")
else:
nc = await nats.connect("nats://nats:4222",user=user,password=password)
try:
response = await nc.request(f"banque.creation",f"{str(user_id_bank)}:1000",timeout=10)
response_data = response.data.decode()
data = response_data.split(",")
status=data[0]
if status == "True":
return Response({'status': 'Account created'}, status=status.HTTP_200_OK)
else:
return Response({'error': 'Account creation failed'}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)



class UserListView(generics.ListCreateAPIView):
queryset = User.objects.all()
Expand Down Expand Up @@ -362,7 +344,7 @@ def post(self, request, *args, **kwargs):



if payment_successful:
if payment_successful == 'True':
booking.status = 'confirmed'
booking.save()

Expand Down
17 changes: 7 additions & 10 deletions NATS/banque/banque.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,31 +43,28 @@ async def handle_payment_request(msg):
data = msg.data.decode()
parts = data.split(':')
client = parts[0]
montant = float(parts[1])



'''
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 = True
response_msg = "True"
save_clients()
else:
print("Paiement refusé.")
response_msg = False
response_msg = "False"
else:
print("Paiement refusé, solde insuffisant.")
response_msg = False
response_msg = "False"
else:
print("Client inconnu.")
response_msg = False
'''
#response_msg = "True"
#await nc.publish("banque.validation", response_msg.encode())
response_msg = "False"

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


except Exception as e:
Expand Down

0 comments on commit 5115ffa

Please sign in to comment.