Skip to content

Instantly share code, notes, and snippets.

@nguyentienlong
Last active March 26, 2018 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nguyentienlong/eb02ffd226be6766b0b5aa40b059d27b to your computer and use it in GitHub Desktop.
Save nguyentienlong/eb02ffd226be6766b0b5aa40b059d27b to your computer and use it in GitHub Desktop.
Booking Resource refactoring 1
from app import log
logger = log.get_logger()
class BookingResource(object):
def __init(self):
pass
def on_put(self, req, resp, booking_id):
try:
data = req.stream().read()
data = json.loads(data.decode('utf-8'))
BookingHandlerFactory.create_hander(data['status']).handle(data)
except Exception as e:
logger.exception(e)
class BookingHandlerFactory(object):
@static_method
def create_handler(status):
if status == 'init':
return InitHandler()
if status == 'accepted':
return AcceptedHandler()
if status == 'deposited':
return DepositedHandler()
if status == 'done':
return DoneHandler():
class IHandler():
def handle(data):
raise Exception('Not implemented')
class InitHandler(IHandler):
def handle(data):
print('this is init handler')
# more logic here
class AcceptedHandler(IHandler):
def handle(data):
print('this is accepted handler')
# more logic here
class DepositedHandler(IHandler):
def handle(data):
print('this is deposited handler')
# more logic here
class DoneHandler(IHandler):
def handle(data):
print('this is done handler')
# more logic here
from app import log
logger = log.get_logger()
class BookingResource(object):
def __init(self):
pass
def on_put(self, req, resp, booking_id):
try:
data = req.stream().read()
data = json.loads(data.decode('utf-8'))
BookingHandlerFactory.create_hander(data['status']).handle(data)
except Exception as e:
logger.exception(e)
# Standard import
import importlib
class BookingHandlerFactory(object):
hanlder_mapping = {
'init': 'InitHandler',
'accepted': 'AcceptedHandler',
'deposited': 'DepositedHandler',
'done': 'DoneHandler',
}
@static_method
def create_handler(status):
# Load "module.submodule.MyClass"
Handler = getattr(importlib.import_module("module.submodule"), handler_mapping[status])
# Instantiate the class (pass arguments to the constructor, if needed)
return Handler()
class IHandler():
def handle(data):
raise Exception('Not implemented')
class InitHandler(IHandler):
def handle(data):
print('this is init handler')
# more logic here
class AcceptedHandler(IHandler):
def handle(data):
print('this is accepted handler')
# more logic here
class DepositedHandler(IHandler):
def handle(data):
print('this is deposited handler')
# more logic here
class DoneHandler(IHandler):
def handle(data):
print('this is done handler')
# more logic here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment