From 70a2dd1de68b864887739fb7f757c1e039ce52e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Wed, 17 Jan 2018 14:26:16 +0100 Subject: [PATCH] =?UTF-8?q?Refactor=20of=20EventHandler=20boilerplate=20?= =?UTF-8?q?=C2=AF\=5F(=E3=83=84)=5F/=C2=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/event_handlers/event_handler.py | 18 ---- src/event_handlers/event_handler_base.py | 12 +++ src/event_handlers/event_handler_main.py | 102 +++++++++--------- .../source_code_event_handler.py | 42 ++++---- 4 files changed, 84 insertions(+), 90 deletions(-) delete mode 100644 src/event_handlers/event_handler.py diff --git a/src/event_handlers/event_handler.py b/src/event_handlers/event_handler.py deleted file mode 100644 index b7f16cc..0000000 --- a/src/event_handlers/event_handler.py +++ /dev/null @@ -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) diff --git a/src/event_handlers/event_handler_base.py b/src/event_handlers/event_handler_base.py index 37a02da..ea8578e 100644 --- a/src/event_handlers/event_handler_base.py +++ b/src/event_handlers/event_handler_base.py @@ -19,6 +19,18 @@ class EventHandlerBase: 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)) + 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): encoded_anchor = anchor.encode('utf-8') diff --git a/src/event_handlers/event_handler_main.py b/src/event_handlers/event_handler_main.py index 8ef9f1d..cd01b9b 100644 --- a/src/event_handlers/event_handler_main.py +++ b/src/event_handlers/event_handler_main.py @@ -3,7 +3,7 @@ import sqlite3 from functools import partial import source_code -from event_handler import EventHandler +from event_handler_base import EventHandlerBase from source_code_event_handler import SourceCodeEventHandler from stateful_event_handler import StatefulEventHandler from tornado.ioloop import IOLoop @@ -16,72 +16,76 @@ login_component_py_response = partial( ) -def echo_handler(data): - return data +class EchoHandler(EventHandlerBase): + def handle_event(self, anchor, data_json): + return data_json -def rot13_handler(data): - data['data'] = codecs.encode(data['data'], 'rot13') - return data +class Rot13Handler(EventHandlerBase): + def handle_event(self, anchor, data_json): + data_json['data'] = codecs.encode(data_json['data'], 'rot13') + return data_json -def change_case_handler(data): - data['data'] = data['data'].upper() if data['data'].islower() else data['data'].lower() - return data +class ChangeCaseHandler(EventHandlerBase): + def handle_event(self, anchor, data_json): + data_json['data'] = data_json['data'].upper() if data_json['data'].islower() else data_json['data'].lower() + return data_json -def reverse_handler(data): - data['data'] = data['data'][::-1] - return data +class ReverseHandler(EventHandlerBase): + def handle_event(self, anchor, data_json): + data_json['data'] = data_json['data'][::-1] + return data_json -def login_handler(data): - email, password = data['data']['email'], data['data']['password'] - try: - sql_statement = source_code.find_local_variable_value(authorize_login, 'sql_statement') - yield ( - 'anchor_logger', - 'The SQL statement executed by the server will look like this:\n `{}`'.format(sql_statement) - ) - - yield ('anchor_webide', - login_component_py_response(content=source_code.get_source_code(authorize_login, strip_comments=False))) - - sql_statement_with_values = sql_statement.format(email, password) - yield ( - 'anchor_logger', - 'After the submitted parameters are substituted it looks like this:\n `{}`'.format( - sql_statement_with_values +class LoginHandler(EventHandlerBase): + def handle_event(self, anchor, data_json): + email, password = data_json['data']['email'], data_json['data']['password'] + try: + sql_statement = source_code.find_local_variable_value(authorize_login, 'sql_statement') + yield ( + 'anchor_logger', + 'The SQL statement executed by the server will look like this:\n `{}`'.format(sql_statement) ) - ) - logged_in_email, is_admin = authorize_login(email, password) + yield ('anchor_webide', + login_component_py_response(content=source_code.get_source_code(authorize_login, strip_comments=False))) - yield ( - 'anchor_logger', - 'After the query is executed, it returns _{}_ as email address, and _{}_ for is_admin'.format( - logged_in_email, is_admin + sql_statement_with_values = sql_statement.format(email, password) + yield ( + 'anchor_logger', + 'After the submitted parameters are substituted it looks like this:\n `{}`'.format( + sql_statement_with_values + ) ) - ) - if logged_in_email is not None: - response = 'Logged in as _{}_. You __{}have__ admin privileges.'.format( - logged_in_email, - '' if is_admin else 'don\'t ' + logged_in_email, is_admin = authorize_login(email, password) + + yield ( + 'anchor_logger', + 'After the query is executed, it returns _{}_ as email address, and _{}_ for is_admin'.format( + logged_in_email, is_admin + ) ) - else: - response = 'Bad username/password!' - except sqlite3.Warning: - response = 'Invalid request!' - yield ('anchor_login', '# Login page\n' + response) + if logged_in_email is not None: + response = 'Logged in as _{}_. You __{}have__ admin privileges.'.format( + logged_in_email, + '' if is_admin else 'don\'t ' + ) + else: + response = 'Bad username/password!' + except sqlite3.Warning: + response = 'Invalid request!' + + yield ('anchor_login', '# Login page\n' + response) if __name__ == '__main__': - anchor_a = EventHandler('anchor_a', change_case_handler) - anchor_b = EventHandler('anchor_b', rot13_handler) - anchor_c = EventHandler('anchor_c', reverse_handler) - anchor_login = StatefulEventHandler('anchor_login', login_handler) + anchor_a = ChangeCaseHandler('anchor_a') + anchor_b = Rot13Handler('anchor_b') + anchor_c = ReverseHandler('anchor_c') anchor_webide = SourceCodeEventHandler('anchor_webide', 'login_component.py', 'login') IOLoop.instance().start() diff --git a/src/event_handlers/source_code_event_handler.py b/src/event_handlers/source_code_event_handler.py index 9f39931..67b3058 100644 --- a/src/event_handlers/source_code_event_handler.py +++ b/src/event_handlers/source_code_event_handler.py @@ -20,29 +20,25 @@ class SourceCodeEventHandler(EventHandlerBase): self.file = self.create_initial_state() - def event_handler_callback(msg_parts): - anchor, message = msg_parts - message_json = json.loads(message) - data = message_json['data'] - if anchor == b'reset': - self.file = self.create_initial_state(process_is_running=True) - if data['command'] == 'read': - with open(self.file, 'r') as ifile: - content = ifile.read() - message_json['data'] = { - 'filename': self.filename, - 'content': content, - 'language': self.language - } - encoded_response = json.dumps(message_json).encode('utf-8') - self.zmq_push_socket.send_multipart([anchor, encoded_response]) - elif data['command'] == 'write': - with open(self.file, 'w') as ofile: - ofile.write(data['content']) - self.supervisor.stopProcess(self.process_name) - self.supervisor.startProcess(self.process_name) - - self.zmq_sub_stream.on_recv(event_handler_callback) + def handle_event(self, anchor, data_json): + data = data_json['data'] + if anchor == b'reset': + self.file = self.create_initial_state(process_is_running=True) + if data['command'] == 'read': + with open(self.file, 'r') as ifile: + content = ifile.read() + data_json['data'] = { + 'filename': self.filename, + 'content': content, + 'language': self.language + } + return data_json + elif data['command'] == 'write': + with open(self.file, 'w') as ofile: + ofile.write(data['content']) + self.supervisor.stopProcess(self.process_name) + self.supervisor.startProcess(self.process_name) + return None def create_initial_state(self, process_is_running=False): if process_is_running: