mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2025-06-28 23:05:12 +00:00
Rearrange project and dockerize
This commit is contained in:
31
src/components/component.py
Normal file
31
src/components/component.py
Normal file
@ -0,0 +1,31 @@
|
||||
import json
|
||||
from functools import partial
|
||||
|
||||
import zmq
|
||||
from zmq.eventloop.zmqstream import ZMQStream
|
||||
from zmq.eventloop import ioloop
|
||||
|
||||
from config import RECEIVER_PORT, PUBLISHER_PORT
|
||||
|
||||
ioloop.install()
|
||||
|
||||
|
||||
class Component:
|
||||
def __init__(self, anchor, event_handler, zmq_context=None):
|
||||
self.anchor = anchor
|
||||
self.event_handler = event_handler
|
||||
self.zmq_context = zmq_context or zmq.Context.instance()
|
||||
self.zmq_sub_socket = self.zmq_context.socket(zmq.SUB)
|
||||
self.zmq_sub_socket.setsockopt_string(zmq.SUBSCRIBE, anchor)
|
||||
self.zmq_sub_socket.connect('tcp://localhost:{}'.format(PUBLISHER_PORT))
|
||||
self.zmq_sub_stream = ZMQStream(self.zmq_sub_socket)
|
||||
self.zmq_push_socket = self.zmq_context.socket(zmq.PUSH)
|
||||
self.zmq_push_socket.connect('tcp://localhost:{}'.format(RECEIVER_PORT))
|
||||
|
||||
def wrapper(msg_parts, handler):
|
||||
anchor, message = msg_parts
|
||||
data_json = json.loads(message)
|
||||
response = json.dumps(handler(data_json)).encode('utf-8')
|
||||
self.zmq_push_socket.send_multipart([anchor, response])
|
||||
|
||||
self.zmq_sub_stream.on_recv(partial(wrapper, handler=event_handler))
|
32
src/components/component_example.py
Normal file
32
src/components/component_example.py
Normal file
@ -0,0 +1,32 @@
|
||||
import codecs
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
from component import Component
|
||||
|
||||
|
||||
def echo_handler(data):
|
||||
return data
|
||||
|
||||
|
||||
def rot13_handler(data):
|
||||
data['data'] = codecs.encode(data['data'], 'rot13')
|
||||
return data
|
||||
|
||||
|
||||
def change_case_handler(data):
|
||||
data['data'] = data['data'].upper() if data['data'].islower() else data['data'].lower()
|
||||
return data
|
||||
|
||||
|
||||
def reverse_handler(data):
|
||||
data['data'] = data['data'][::-1]
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
anchor_a = Component('anchor_a', change_case_handler)
|
||||
anchor_b = Component('anchor_b', rot13_handler)
|
||||
anchor_c = Component('anchor_c', reverse_handler)
|
||||
|
||||
IOLoop.instance().start()
|
Reference in New Issue
Block a user