52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
import json
|
|
import os
|
|
|
|
import pika
|
|
|
|
|
|
def connection():
|
|
parameters = pika.URLParameters(os.environ["BROKER_URL"])
|
|
parameters.heartbeat = 30
|
|
return pika.BlockingConnection(parameters)
|
|
|
|
|
|
def ensure_topology():
|
|
conn = connection()
|
|
channel = conn.channel()
|
|
channel.exchange_declare(exchange="attachment.events", exchange_type="topic", durable=True)
|
|
channel.queue_declare(
|
|
queue="attachment.processing",
|
|
durable=True,
|
|
arguments={"x-dead-letter-exchange": "attachment.events", "x-dead-letter-routing-key": "attachment.failed"},
|
|
)
|
|
channel.queue_declare(queue="attachment.failed", durable=True)
|
|
channel.queue_bind(queue="attachment.processing", exchange="attachment.events", routing_key="attachment.process")
|
|
channel.queue_bind(queue="attachment.failed", exchange="attachment.events", routing_key="attachment.failed")
|
|
conn.close()
|
|
|
|
|
|
def publish(job, routing_key="attachment.process"):
|
|
conn = connection()
|
|
try:
|
|
channel = conn.channel()
|
|
channel.confirm_delivery()
|
|
channel.exchange_declare(exchange="attachment.events", exchange_type="topic", durable=True)
|
|
channel.queue_declare(
|
|
queue="attachment.processing",
|
|
durable=True,
|
|
arguments={"x-dead-letter-exchange": "attachment.events", "x-dead-letter-routing-key": "attachment.failed"},
|
|
)
|
|
channel.basic_publish(
|
|
exchange="attachment.events",
|
|
routing_key=routing_key,
|
|
body=json.dumps(job, ensure_ascii=False).encode("utf-8"),
|
|
properties=pika.BasicProperties(
|
|
content_type="application/json",
|
|
delivery_mode=2,
|
|
message_id=job["job_id"],
|
|
),
|
|
mandatory=True,
|
|
)
|
|
finally:
|
|
conn.close()
|