send.py 1.46 KB
Newer Older
1
from flask_restful import Resource, request, abort
Dan Jones's avatar
Dan Jones committed
2
from marshmallow import Schema, fields
3
import pika
4 5
import json

6 7 8 9 10
class SendSchema(Schema):
    client_id = fields.Str(required=True)
    secret = fields.Str(required=True)
    body = fields.Str(required=True)
    topic = fields.Str(required=True)
11 12

class Send(Resource):
13 14
    clients = None
    schema = None
15

16
    def __init__(self):
17
        self.schema = SendSchema()
18 19
        with open("clients.json", "r") as clients_file:
            self.clients = json.load(clients_file)
20

21
    def post(self):
22 23
        args = request.get_json()
        errors = self.schema.validate(args)
24
        if errors:
25
            abort(400, message=str(errors))
26

27
        allow = False
28 29 30
        body = args.get("body")
        topic = args.get("topic")
        client_id = args.get("client_id")
31 32 33
        outbox_queue = client_id + "-outbox"
        if client_id in self.clients:
            client = self.clients.get(client_id)
34
            if args.get("secret") == client.get("secret"):
35 36 37 38 39
                allow = True

        if allow:
            connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
            channel = connection.channel()
40
            channel.queue_declare(queue=outbox_queue, durable=True)
41 42 43 44
            message = {
                'topic': topic,
                'message': body,
            }
45 46
            channel.basic_publish(exchange="", routing_key=outbox_queue, body=json.dumps(message))
            connection.close()