Skip to content

Instantly share code, notes, and snippets.

@fcracker79
Created January 3, 2019 08:36
Show Gist options
  • Save fcracker79/bec718d0214db7c1b7bb67b31e1c605a to your computer and use it in GitHub Desktop.
Save fcracker79/bec718d0214db7c1b7bb67b31e1c605a to your computer and use it in GitHub Desktop.
import collections
_ApiMethod = collections.namedtuple('_ApiMethod', ['name', 'path', 'http_method', 'query_params'])
API = [
_ApiMethod('print_hello', 'api/hello', "GET", ['limit']),
]
class Meta(type):
def __new__(mcs, *args, **kwargs):
o = super(Meta, mcs).__new__(mcs, *args, **kwargs)
def _add_methods():
def _build_method(path, http_method, expected_query_params):
if http_method == "GET":
def _method(self, **method_kwargs):
query_params = kwargs.setdefault('query_params', {})
query_params.update({qp: kwargs[qp] for qp in expected_query_params if qp in method_kwargs})
return self.get(path=path, **method_kwargs)
else:
raise NotImplementedError
return _method
for api_method in API:
setattr(
o, api_method.name,
_build_method(api_method.path, api_method.http_method, api_method.query_params or []))
_add_methods()
return o
class HelloClient(metaclass=Meta):
# Commented out as it is broken
# def __repr__(self):
# return "HelloClient(%s)" % ', '.join('%s=%s' % (a, repr(getattr(self, a))) for a in ['url', 'headers'])
# noinspection PyUnusedLocal,PyMethodMayBeStatic
def get(self, path, query_params=None, headers=None, **kwargs):
return "I am Hello Get Method"
client = HelloClient()
# noinspection PyUnresolvedReferences
response = client.print_hello()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment