-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_listener.py
89 lines (78 loc) · 2.85 KB
/
http_listener.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# -*- coding: utf-8 -*-
from uuid import uuid4
from twisted.web import server, resource
from twisted.python import log
from twisted.internet import reactor, endpoints
import pika
CRED = 'lv128'
HOST = 'localhost'
RABBITMQ_PORT = 5672
QUEUE_HTTPLISTENER = "httplistener"
QUEUE_VALIDATION = "validation.messages"
LOG_PATH_1 = "/opt/lv128/log/validation_queue.log"
LOG_PATH_2 = '/opt/lv128/log/HTTPListener.log'
PORT = "tcp:8812"
COUNT = 1
class HTTPListener(resource.Resource):
isLeaf = True
def __init__(self):
credentials = pika.PlainCredentials(CRED, CRED)
parameters = pika.ConnectionParameters(HOST,
RABBITMQ_PORT,
'/',
credentials)
try:
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
except:
raise
def render_GET(self, request):
request.setHeader("content-type", "text/plain")
message = request.args.get("msg")
if message and isinstance(message, list):
message = message[0]
log.msg(message)
return "OK-GET"
def render_POST(self, request):
"""
The function listens to POST-request from client and return valid message
"""
request.setHeader("content-type", "text/plain")
message = request.args.get("msg", "")
token = request.args.get("token", "")
if message and isinstance(message, list):
message = message[0]
if token and isinstance(token, list):
token = token[0]
triplet = ':'.join([uuid4().hex, token, message])
self.send_msg(QUEUE_VALIDATION, triplet)
with open(LOG_PATH_1, "a+") as validation_file:
validation_file.write(triplet + '\n')
log.msg(message)
resp = self.get_msg(QUEUE_HTTPLISTENER)
log.msg(resp)
if resp:
code, msg = resp.split('|')
request.setResponseCode(int(code))
return msg
def send_msg(self, my_queue, my_msg):
"""
The function declares a queue and send message there
"""
self.channel.queue_declare(my_queue)
self.channel.basic_publish(exchange='', routing_key=my_queue, body=str(my_msg))
def get_msg(self, my_queue):
"""
The function takes message from the queue
"""
self.channel.basic_qos(prefetch_count=COUNT)
try:
for method_frame, properties, body in self.channel.consume(my_queue):
self.channel.basic_ack(method_frame.delivery_tag)
return body
except pika.exceptions, err_msg:
log.error(err_msg)
return False
log.startLogging(open(LOG_PATH_2, 'w'))
endpoints.serverFromString(reactor, PORT).listen(server.Site(HTTPListener()))
reactor.run()