Last active
August 29, 2015 14:01
-
-
Save gtato/45dee18aa99a59d19059 to your computer and use it in GitHub Desktop.
A simple mechanism for allowing HTTP servers to add request handlers (managers) dynamically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exposed_functions_http_methods = {} | |
def expose(http_method): | |
def decorator(func): | |
exposed_functions_http_methods[id(func)] = http_method | |
def wrapped(self, *args, **kwargs): | |
return func(self, *args, **kwargs) | |
return wrapped | |
return decorator | |
class BaseManager(object): | |
def __init__(self): | |
self.a = "hello" | |
self.exposed_functions = {} | |
@expose("POST") | |
def hello(self): | |
print self.a | |
@expose("POST") | |
def kitty(self): | |
print 'base kitty' | |
def get_exposed_methods(self): | |
wrap_func_name = 'wrapped' | |
for attr_name in dir(self): | |
attr = object.__getattribute__(self, attr_name) | |
if hasattr(attr, 'im_self'): | |
if attr.im_func.__name__ == wrap_func_name: | |
if attr.func_closure and attr.func_closure[0] and attr.func_closure[0].cell_contents: | |
method_id = id( attr.func_closure[0].cell_contents) | |
http_method = exposed_functions_http_methods[method_id] | |
if http_method not in self.exposed_functions: | |
self.exposed_functions[http_method] = {} | |
self.exposed_functions[http_method][attr_name] = attr | |
return self.exposed_functions | |
class PHPManager(BaseManager): | |
def __init__(self): | |
BaseManager.__init__(self) | |
self.a = "hellophp" | |
@expose("POST") | |
def hello(self): | |
print self.a | |
class JavaManager(BaseManager): | |
def __init__(self): | |
BaseManager.__init__(self) | |
self.a = "hellojava" | |
self.b = "worldjava" | |
@expose("POST") | |
def hello(self): | |
print self.a | |
@expose("GET") | |
def world(self): | |
print self.b | |
bm = BaseManager() | |
phpm = PHPManager() | |
javam = JavaManager() | |
javam.get_exposed_methods()['POST']['kitty']() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment