ca4006-ca2/university.py
Malachy Byrne 41adade9fc
Added withdrawal capabilities.
TODO: improve logging, have researchers make use of withdrawal
2023-04-13 04:28:10 +01:00

47 lines
1.9 KiB
Python

import pika
import os
import pickle
from functions import log, save_project
from classes import *
class University:
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, '/', pika.PlainCredentials("user", "password")))
self.channel = self.connection.channel()
self.channel.queue_declare(queue='university_project')
self.channel.queue_declare(queue='withdraw_funds')
self.channel.basic_consume(queue="university_project", on_message_callback=self.receive_response, auto_ack=True)
self.channel.basic_consume(queue="withdraw_funds", on_message_callback=self.withdraw_funds, auto_ack=True)
self.response = None
self.corr_id = None
def receive_response(self, ch, method, properties, body):
self.response = body
project = pickle.loads(self.response)
transaction = Transaction(self.name, int(self.amount))
project.history.append(transaction)
project.amount -= int(self.amount)
if project.amount >= 0:
save_project(project)
log(f"{self.name} withdrew {self.amount} from {project.acronym}. {project.amount} remaining")
else:
log(f"{self.name} attempter to withdraw {self.amount} from {project.acronym} but there was only {project.amount + int(self.amount)} remaining")
def withdraw_funds(self, ch, method, properties, body):
body = body.decode()
proj_id, self.name, self.amount = body.split(',')
self.channel.basic_publish(exchange='', routing_key='get_project',
properties=pika.BasicProperties(reply_to="university_project"),
body=proj_id)
try:
university = University()
university.channel.start_consuming()
except KeyboardInterrupt:
university.channel.stop_consuming()
university.connection.close()