send.py 1.47 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 4
import json

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

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

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

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

26 27
        messages = []
        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 40 41 42 43 44 45 46
                allow = True

        if allow:
            connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
            channel = connection.channel()
            channel.queue_declare(queue=notify_queue, durable=True)
            message = {
                'topic': topic,
                'message': body,
            }
            channel.basic_publish(exchange="", routing_key=notify_queue, body=message)
            deliver_connection.close()