Skip to content

Instantly share code, notes, and snippets.

@shauns
Created July 28, 2014 11:32
Show Gist options
  • Save shauns/a5e269fc5d6f76ecb3e8 to your computer and use it in GitHub Desktop.
Save shauns/a5e269fc5d6f76ecb3e8 to your computer and use it in GitHub Desktop.
Nameko entrypoint sketch
# re: nameko entrypoints
def wrapt_entrypoint(entrypoint_fn=None, provider=None):
""" Transform a callable into a decorator that can be used to declare
entrypoints.
The callable should indicate a EntrypointProvider class. Usages of the
callable will have their kwargs combined with the provider to produce a
DependencyFactory for the given wrapped service function.
The returned ``wrapper`` function has a ``provider_cls`` attribute that
references the EntrypointProvider subclass returned by its factory. This
helps separate the ``@entrypoint`` decorated methods from the class
that implements the dependency - users only need to refer to the method
and nameko can determine the implementing class.
e.g.::
# For 'plain' entrypoints
@wrapt_entrypoint(provider=HttpEntrypoint)
def http(service_fn, instance, args, kwargs):
# Entrypoints are decorators around an underlying function
res = service_fn(*args, **kwargs)
return res
class Service(object):
@http
def foobar():
pass
# Or, for entrypoints with options
def http(service_fn=None, bind_port=80):
if service_fn is None:
return partial(http, bind_port=bind_port)
@wrapt_entrypoint(provider=http.provider_cls)
def wrapper(service_fn, instance, args, kwargs):
return service_fn(*args, **kwargs)
return wrapper(service_fn, bind_port=80)
http.provider_cls = HttpEntrypoint
"""
if entrypoint_fn is not None:
def factory_registering(wrapped, instance, args, factory_kwargs):
# We should always have the target function to be wrapped at
# this point as the first (and only) value in args.
service_fn = args[0]
factory = DependencyFactory(provider, **factory_kwargs)
register_entrypoint(service_fn, factory)
assert instance is None and not inspect.isclass(wrapped)
# Finally build the wrapper itself and return it.
return FunctionWrapper(service_fn, entrypoint_fn)
entrypoint_fn.provider_cls = provider
return FunctionWrapper(entrypoint_fn, factory_registering)
else:
# We've just been collecting kwargs for the wrapper, so re-apply.
return partial(wrapt_entrypoint, provider=provider)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment