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,72 +16,76 @@ 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):
try: email, password = data_json['data']['email'], data_json['data']['password']
sql_statement = source_code.find_local_variable_value(authorize_login, 'sql_statement') try:
yield ( sql_statement = source_code.find_local_variable_value(authorize_login, 'sql_statement')
'anchor_logger', yield (
'The SQL statement executed by the server will look like this:\n `{}`'.format(sql_statement) '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
) )
)
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 ( sql_statement_with_values = sql_statement.format(email, password)
'anchor_logger', yield (
'After the query is executed, it returns _{}_ as email address, and _{}_ for is_admin'.format( 'anchor_logger',
logged_in_email, is_admin 'After the submitted parameters are substituted it looks like this:\n `{}`'.format(
sql_statement_with_values
)
) )
)
if logged_in_email is not None: logged_in_email, is_admin = authorize_login(email, password)
response = 'Logged in as _{}_. You __{}have__ admin privileges.'.format(
logged_in_email, yield (
'' if is_admin else 'don\'t ' '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__': 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) if anchor == b'reset':
data = message_json['data'] self.file = self.create_initial_state(process_is_running=True)
if anchor == b'reset': if data['command'] == 'read':
self.file = self.create_initial_state(process_is_running=True) with open(self.file, 'r') as ifile:
if data['command'] == 'read': content = ifile.read()
with open(self.file, 'r') as ifile: data_json['data'] = {
content = ifile.read() 'filename': self.filename,
message_json['data'] = { 'content': content,
'filename': self.filename, 'language': self.language
'content': content, }
'language': self.language return data_json
} elif data['command'] == 'write':
encoded_response = json.dumps(message_json).encode('utf-8') with open(self.file, 'w') as ofile:
self.zmq_push_socket.send_multipart([anchor, encoded_response]) ofile.write(data['content'])
elif data['command'] == 'write': self.supervisor.stopProcess(self.process_name)
with open(self.file, 'w') as ofile: self.supervisor.startProcess(self.process_name)
ofile.write(data['content']) return None
self.supervisor.stopProcess(self.process_name)
self.supervisor.startProcess(self.process_name)
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: