Refactor of EventHandler boilerplate ¯\_(ツ)_/¯

This commit is contained in:
Kristóf Tóth 2018-01-17 14:26:16 +01:00
parent f713697a2e
commit 70a2dd1de6
4 changed files with 84 additions and 90 deletions

View File

@ -1,18 +0,0 @@
import json
from event_handler_base import EventHandlerBase
class EventHandler(EventHandlerBase):
def __init__(self, anchor, event_handler_function, zmq_context=None):
super().__init__(anchor, zmq_context)
self.event_handler_function = event_handler_function
def event_handler_callback(msg_parts):
anchor, message = msg_parts
data_json = json.loads(message)
response = self.event_handler_function(data_json)
encoded_response = json.dumps(response).encode('utf-8')
self.zmq_push_socket.send_multipart([anchor, encoded_response])
self.zmq_sub_stream.on_recv(event_handler_callback)

View File

@ -19,6 +19,18 @@ class EventHandlerBase:
self.zmq_sub_stream = ZMQStream(self.zmq_sub_socket) self.zmq_sub_stream = ZMQStream(self.zmq_sub_socket)
self.zmq_push_socket = self.zmq_context.socket(zmq.PUSH) self.zmq_push_socket = self.zmq_context.socket(zmq.PUSH)
self.zmq_push_socket.connect('tcp://localhost:{}'.format(RECEIVER_PORT)) self.zmq_push_socket.connect('tcp://localhost:{}'.format(RECEIVER_PORT))
self.zmq_sub_stream.on_recv(self.event_handler_callback)
def event_handler_callback(self, msg_parts):
anchor, message = msg_parts
data_json = json.loads(message)
response = self.handle_event(anchor, data_json)
if response is None: return
encoded_response = json.dumps(response).encode('utf-8')
self.zmq_push_socket.send_multipart([anchor, encoded_response])
def handle_event(self, anchor, data_json):
raise NotImplementedError
def message_other(self, anchor, data): def message_other(self, anchor, data):
encoded_anchor = anchor.encode('utf-8') encoded_anchor = anchor.encode('utf-8')

View File

@ -3,7 +3,7 @@ import sqlite3
from functools import partial from functools import partial
import source_code import source_code
from event_handler import EventHandler from event_handler_base import EventHandlerBase
from source_code_event_handler import SourceCodeEventHandler from source_code_event_handler import SourceCodeEventHandler
from stateful_event_handler import StatefulEventHandler from stateful_event_handler import StatefulEventHandler
from tornado.ioloop import IOLoop from tornado.ioloop import IOLoop
@ -16,27 +16,32 @@ login_component_py_response = partial(
) )
def echo_handler(data): class EchoHandler(EventHandlerBase):
return data def handle_event(self, anchor, data_json):
return data_json
def rot13_handler(data): class Rot13Handler(EventHandlerBase):
data['data'] = codecs.encode(data['data'], 'rot13') def handle_event(self, anchor, data_json):
return data data_json['data'] = codecs.encode(data_json['data'], 'rot13')
return data_json
def change_case_handler(data): class ChangeCaseHandler(EventHandlerBase):
data['data'] = data['data'].upper() if data['data'].islower() else data['data'].lower() def handle_event(self, anchor, data_json):
return data data_json['data'] = data_json['data'].upper() if data_json['data'].islower() else data_json['data'].lower()
return data_json
def reverse_handler(data): class ReverseHandler(EventHandlerBase):
data['data'] = data['data'][::-1] def handle_event(self, anchor, data_json):
return data data_json['data'] = data_json['data'][::-1]
return data_json
def login_handler(data): class LoginHandler(EventHandlerBase):
email, password = data['data']['email'], data['data']['password'] def handle_event(self, anchor, data_json):
email, password = data_json['data']['email'], data_json['data']['password']
try: try:
sql_statement = source_code.find_local_variable_value(authorize_login, 'sql_statement') sql_statement = source_code.find_local_variable_value(authorize_login, 'sql_statement')
yield ( yield (
@ -78,10 +83,9 @@ def login_handler(data):
if __name__ == '__main__': if __name__ == '__main__':
anchor_a = EventHandler('anchor_a', change_case_handler) anchor_a = ChangeCaseHandler('anchor_a')
anchor_b = EventHandler('anchor_b', rot13_handler) anchor_b = Rot13Handler('anchor_b')
anchor_c = EventHandler('anchor_c', reverse_handler) anchor_c = ReverseHandler('anchor_c')
anchor_login = StatefulEventHandler('anchor_login', login_handler)
anchor_webide = SourceCodeEventHandler('anchor_webide', 'login_component.py', 'login') anchor_webide = SourceCodeEventHandler('anchor_webide', 'login_component.py', 'login')
IOLoop.instance().start() IOLoop.instance().start()

View File

@ -20,29 +20,25 @@ class SourceCodeEventHandler(EventHandlerBase):
self.file = self.create_initial_state() self.file = self.create_initial_state()
def event_handler_callback(msg_parts): def handle_event(self, anchor, data_json):
anchor, message = msg_parts data = data_json['data']
message_json = json.loads(message)
data = message_json['data']
if anchor == b'reset': if anchor == b'reset':
self.file = self.create_initial_state(process_is_running=True) self.file = self.create_initial_state(process_is_running=True)
if data['command'] == 'read': if data['command'] == 'read':
with open(self.file, 'r') as ifile: with open(self.file, 'r') as ifile:
content = ifile.read() content = ifile.read()
message_json['data'] = { data_json['data'] = {
'filename': self.filename, 'filename': self.filename,
'content': content, 'content': content,
'language': self.language 'language': self.language
} }
encoded_response = json.dumps(message_json).encode('utf-8') return data_json
self.zmq_push_socket.send_multipart([anchor, encoded_response])
elif data['command'] == 'write': elif data['command'] == 'write':
with open(self.file, 'w') as ofile: with open(self.file, 'w') as ofile:
ofile.write(data['content']) ofile.write(data['content'])
self.supervisor.stopProcess(self.process_name) self.supervisor.stopProcess(self.process_name)
self.supervisor.startProcess(self.process_name) self.supervisor.startProcess(self.process_name)
return None
self.zmq_sub_stream.on_recv(event_handler_callback)
def create_initial_state(self, process_is_running=False): def create_initial_state(self, process_is_running=False):
if process_is_running: if process_is_running: