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

46 lines
1.5 KiB
Python

import pika
import pickle
import os
from classes import Project, Transaction
from functions import log
if not os.path.exists("approved_projects"):
os.makedirs("approved_projects")
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672, '/', pika.PlainCredentials("user", "password")))
channel = connection.channel()
channel.queue_declare(queue='get_project')
channel.queue_declare(queue='save_project')
def get_project(ch, method, properties, body):
project_id = body.decode()
with open(os.path.join("approved_projects", f"{project_id}.txt"), "rb") as file:
project = file.read()
channel.basic_publish(exchange='',
routing_key=properties.reply_to,
properties=pika.BasicProperties(correlation_id=properties.correlation_id),
body=project)
log(f"Replying to {properties.reply_to}")
log(f"got project {project_id}")
def save_project(ch, method, properties, body):
project = pickle.loads(body)
filename = os.path.join("approved_projects", f"{project.acronym}.txt")
with open(filename, "wb+") as file:
pickle.dump(project, file)
channel.basic_consume(queue='get_project', on_message_callback=get_project, auto_ack=True)
channel.basic_consume(queue='save_project', on_message_callback=save_project, auto_ack=True)
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.stop_consuming()
connection.close()