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()