import pika import os import pickle from functions import log, save_project from classes import * import colours 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 self.name = None self.amount = 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.status == 1: if project.amount >= 0: save_project(project) log(f"{colours.INFO}{self.name}{colours.RESET} withdrew {colours.OK}{self.amount}{colours.RESET} from {colours.INFO}{project.acronym}{colours.RESET}. {colours.INFO}{project.amount}{colours.RESET} remaining") else: log(f"{colours.INFO}{self.name}{colours.RESET} attempted to withdraw {colours.ERROR}{self.amount}{colours.RESET} from {colours.INFO}{project.acronym}{colours.RESET} but there was only {colours.ERROR}{project.amount + int(self.amount)}{colours.RESET} remaining") else: log(f"{colours.INFO}{self.name}{colours.RESET} attempted to withdraw from {colours.WARN}{project.acronym}{colours.RESET} but the project was not approved") def withdraw_funds(self, ch, method, properties, body): body = body.decode() proj_id, name, amount = body.split(',') self.name = name self.amount = amount 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()