-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
62 lines (46 loc) · 1.49 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import argparse
import os
from textwrap import wrap
import pika
from reportlab.pdfgen import canvas
parser = argparse.ArgumentParser()
parser.add_argument("user", help="RabbitMQ user")
parser.add_argument("password", help="RabbitMQ password")
args = parser.parse_args()
url = f'amqp://{args.user}:{args.password}@localhost/pdf-processor'
print(f'RabbitMQ URL: {url}')
params = pika.URLParameters(url)
params.socket_timeout = 5
# connect to RabbitMQ broker
print('Connecting...')
connection = pika.BlockingConnection(params)
channel = connection.channel()
print('Connected')
def create_pdf(msg):
text = msg.decode()
print(f'Creating PDF from {text}')
c = canvas.Canvas("/tmp/out.pdf")
y = 800
for line in wrap(text, 100):
print(line)
c.drawString(15, y, line)
y -= 15
c.save()
return
def on_request(ch, method, props, body):
create_pdf(body)
file = open("/tmp/out.pdf", "rb")
data = file.read()
os.remove("/tmp/out.pdf")
ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id=props.correlation_id), body=data)
ch.basic_ack(delivery_tag=method.delivery_tag)
# create a queue
print('Creating queue')
channel.queue_declare(queue='pdf-processor')
print('Queue created')
# set up subscription on the queue
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='pdf-processor', on_message_callback=on_request)
# start consuming (blocks)
channel.start_consuming()
connection.close()