Skip to content

Instantly share code, notes, and snippets.

@eirenik0
Created February 20, 2019 20:27
Show Gist options
  • Save eirenik0/17d7039b3224c0a8e0d611166ace598b to your computer and use it in GitHub Desktop.
Save eirenik0/17d7039b3224c0a8e0d611166ace598b to your computer and use it in GitHub Desktop.
Create methods dynamically in Python with a creation factory
def create_request_factory(timeout, headers, api_session_running_url):
methods = ("post", "get", "delete", "long_post", "long_get", "long_delete")
class _Request(object):
def __init__(self, com):
self._com = com
class RequestFactory(object):
def __init__(self):
self._com = None
def create(self, api_key, server_url):
if self._com:
return self._com
self._com = _RequestCommunicator(
timeout,
headers,
api_key,
endpoint_uri=urljoin(server_url, api_session_running_url),
)
request = _Request(self._com)
# self._build_request_methods(request)
return request
def _build_request_methods(self, request):
for method_name in methods:
setattr(self, method_name, self._create_method(method_name))
return request
def _create_method(self, method_name):
func = (
self._com.long_request
if method_name.startswith("long")
else self._com.request
)
def request_method(url_resource=None, **kwargs):
requests_method = getattr(requests, method_name.lstrip("long_"))
return func(requests_method, url_resource, **kwargs)
request_method.__name__ = method_name
request_method.__doc__ = "Make call"
return request_method
return RequestFactory()
request_factory = create_request_factory(
timeout=ServerConnector.DEFAULT_TIMEOUT,
headers=ServerConnector.DEFAULT_HEADERS,
api_session_running_url=ServerConnector.API_SESSIONS_RUNNING,
)
_request = self._request_factory.create(
server_url=self.server_url, api_key=self.api_key
)
response = _request.post(
url_resource="data", data=dom_bytes, headers=headers
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment