ibmresilient/resilient-python-api

No way to pass headers with Python package

teranpeterson opened this issue · 1 comments

Description

The get, post and other methods provided in the Resilient Python package do not provide a way for users to pass header options.

Describe How to Reproduce

def get(self, uri, co3_context_token=None, timeout=None)
Only option is to provide a co3 context token

Example monkey patch for a POST request if anyone is looking:

POST request function in Simple Client:

def new_post(self, uri, payload, headers=None, co3_context_token=None, timeout=None):
    # Hot rewrite for the post function in resilient.co3.SimpleClient to allow passing headers
    response = None
    try:
        # Calls the base class monkey patched below
        response = super(resilient.co3.SimpleClient, self).post(uri, payload, headers, co3_context_token, timeout)
    except resilient.co3base.BasicHTTPException as ex:
        resilient.co3._raise_if_error(ex.get_response())
    return response

POST request function in Base Client:

def new_base_post(self, uri, payload, headers=None, co3_context_token=None, timeout=None):
    # Hot rewrite for the post function in the resilient.co3base.BaseClient to allow passing headers
    url = u"{0}/rest/orgs/{1}{2}".format(self.base_url, self.org_id, resilient.co3base.ensure_unicode(uri))
    payload_json = dumps(payload)
    response = self._execute_request(self.session.post,
                                     url,
                                     data=payload_json,
                                     proxies=self.proxies,
                                     cookies=self.cookies,
                                     # Here the additional 'headers' value is passed to
                                     # self.make_headers() which already supports this parameter
                                     headers=self.make_headers(co3_context_token, headers),
                                     verify=self.verify,
                                     timeout=timeout)
    resilient.co3base.BasicHTTPException.raise_if_error(response)
    return loads(response.text)

Later in your code before calling post:

# Apply Monkey Patch
resilient.co3.SimpleClient.post = new_post
resilient.co3base.BaseClient.post = new_base_post

Then call a POST request like normal with additional dictionary parameter:

client = resilient.get_client(opts)
resp = client.post(uri, body, headers)

This same monkey patch works for any other request function. The make_headers() function in the BaseClient class already accepts a dictionary of headers as a parameter. So the rewrite just needs to pass a dictionary to that function and it takes care of the rest.