Added project server to be used by other endpoints

This commit is contained in:
Malachy Byrne 2023-04-12 18:14:41 +01:00
parent 05e0e1e9e4
commit a1d455df2a
Signed by: malmal200
GPG Key ID: EC21443030A655D9
3 changed files with 72 additions and 19 deletions

30
classes.py Normal file
View File

@ -0,0 +1,30 @@
from dataclasses import dataclass, field
import pickle
from typing import List
@dataclass
class Transaction:
person: str
value: int
description: str
@dataclass
class Project:
acronym: str
title: str
description: str
amount: int
history: List[Transaction] = field(default_factory=list)
if __name__ == "__main__":
history = [Transaction(f"person {i}", i, f"description {i}") for i in range(10)]
project1 = Project("acronym", "title", "description", 500, history)
with open("file", "wb+") as file1:
pickle.dump(project1, file1)
with open("file", "rb") as file2:
project2 = pickle.load(file2)
print(project2)

View File

@ -1,19 +0,0 @@
from dataclasses import dataclass
import pickle
@dataclass
class Project:
acronym: str
title: str
description: str
amount: int
if __name__ == "__main__":
project1 = Project("acronym", "title", "description", 500)
with open("file", "wb+") as file1:
pickle.dump(project1, file1)
with open("file", "rb") as file2:
project2 = pickle.load(file2)
print(project2)

42
project_server.py Normal file
View File

@ -0,0 +1,42 @@
import pika
import pickle
import os
from classes import Project
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)
print(f"got project {project_id}")
def save_project(ch, method, properties, body):
project_data = body.decode()
acronym, title, description, amount = project_data.split(',')
project = Project(acronym, title, description, int(amount))
filename = os.path.join("approved_projects", f"{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=False)
channel.basic_consume(queue='save_project', on_message_callback=save_project, auto_ack=True)
channel.start_consuming()