mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-12-23 03:01:56 +00:00
Refactor of EventHandler boilerplate ¯\_(ツ)_/¯
This commit is contained in:
parent
f713697a2e
commit
70a2dd1de6
@ -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)
|
@ -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')
|
||||
|
@ -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()
|
||||
|
||||
|
@ -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:
|
||||
|
Loading…
Reference in New Issue
Block a user