@@ -68,6 +68,47 @@ def new_f(*args, **kwargs):
6868 return new_f
6969
7070
71+ def parse_cookies (cookie_str , dictionary ):
72+ """Tries to parse any key-value pairs of cookies in a string,
73+ then updates the the dictionary with any key-value pairs found.
74+
75+ **Example**::
76+
77+ parse_cookies('my=value', {})
78+ # Now the following is True
79+ dictionary['my'] == 'value'
80+
81+ :param cookie_str: A string containing "key=value" pairs from an HTTP "Set-Cookie" header
82+ :type msg: ``str``
83+ :param dictionary: A dictionary to update with any found key-value pairs
84+ :type msg: ``dict``
85+ """
86+ parsed_cookie = Cookie .SimpleCookie (cookie_str )
87+ for cookie in parsed_cookie .values ():
88+ dictionary [cookie .key ] = cookie .coded_value
89+
90+ def make_cookie_header (cookies ):
91+ # TODO: verify
92+ """
93+ Takes a list of 2-tuples of key-value pairs of
94+ cookies, and returns a valid HTTP ``Cookie``
95+ header.
96+
97+ **Example**::
98+
99+ header = make_cookie_header([("key", "value"), ("key_2", "value_2")])
100+ # Now the following is True
101+ header == "key=value; key_2=value_2"
102+
103+ :param cookies:
104+ :return: ``str` An HTTP header cookie string.
105+ :rtype: ``str``
106+ """
107+ header = ""
108+ for key , value in cookies :
109+ header += "%s=%s; " % (key , value )
110+ return header
111+
71112# Singleton values to eschew None
72113class _NoAuthenticationToken (object ):
73114 """The value stored in a :class:`Context` or :class:`splunklib.client.Service`
@@ -226,7 +267,7 @@ def f():
226267 @wraps (request_fun )
227268 def wrapper (self , * args , ** kwargs ):
228269 if self .token is _NoAuthenticationToken and \
229- len (self .cookies ) < 1 :
270+ len (self .http . cookies ) < 1 :
230271 # Not yet logged in.
231272 if self .autologin and self .username and self .password :
232273 # This will throw an uncaught
@@ -430,12 +471,9 @@ def __init__(self, handler=None, **kwargs):
430471 self .password = kwargs .get ("password" , "" )
431472 self .autologin = kwargs .get ("autologin" , False )
432473
433- # By default, there are no cookies
434- self .cookies = {}
474+ # Store any cookies in the self.http.cookies dict
435475 if kwargs .has_key ("cookie" ) and kwargs ['cookie' ] not in [None , _NoAuthenticationToken ]:
436- parsed_cookie = Cookie .SimpleCookie (kwargs .get (("cookie" )))
437- for cookie in parsed_cookie .values ():
438- self .cookies [cookie .key ] = cookie .coded_value
476+ parse_cookies (kwargs ["cookie" ], self .http .cookies )
439477
440478 # Shared per-context request headers
441479 @property
@@ -448,8 +486,8 @@ def _auth_headers(self):
448486
449487 :returns: A list of 2-tuples containing key and value
450488 """
451- if len (self .cookies ) > 0 :
452- return [("cookie " , "%s=%s" % cookie ) for cookie in self .cookies .items ()]
489+ if len (self .http . cookies ) > 0 :
490+ return [("Cookie " , make_cookie_header ( self .http . cookies .items ()) )]
453491 elif self .token is _NoAuthenticationToken :
454492 return []
455493 else :
@@ -766,8 +804,8 @@ def login(self):
766804 c = binding.Context(...).login()
767805 # Then issue requests...
768806 """
769- # If self.cookies and self.token only, use the cookie
770- if len (self .cookies ) > 0 and \
807+
808+ if len (self .http . cookies ) > 0 and \
771809 (not self .username and not self .password ):
772810 # If we were passed session cookie(s), but no username or
773811 # password, then login is a nop, since we're automatically
@@ -789,14 +827,6 @@ def login(self):
789827 password = self .password ,
790828 cookie = "1" ) # In Splunk 6.2+, passing "cookie=1" will return the "set-cookie" header
791829
792- # Store the cookie
793-
794- for key , value in response .headers :
795- if key .lower () == "set-cookie" :
796- parsed_cookies = Cookie .SimpleCookie (value )
797- for cookie in parsed_cookies .values ():
798- self .cookies [cookie .key ] = cookie .coded_value
799-
800830 body = response .body .read ()
801831 session = XML (body ).findtext ("./sessionKey" )
802832 self .token = "Splunk %s" % session
@@ -810,7 +840,7 @@ def login(self):
810840 def logout (self ):
811841 """Forgets the current session token, and cookies."""
812842 self .token = _NoAuthenticationToken
813- self .cookies = {}
843+ self .http . cookies = {}
814844 return self
815845
816846 def _abspath (self , path_segment ,
@@ -1151,11 +1181,16 @@ def request(self, url, message, **kwargs):
11511181 raise HTTPError (response )
11521182
11531183 # Update the cookie with any HTTP request
1154- for key , value in response .headers :
1184+ # Initially, assume list of 2-tuples
1185+ key_value_tuples = response .headers
1186+ # If response.headers is a dict, get the key-value pairs as 2-tuples
1187+ # this is the case when using urllib2
1188+ if isinstance (response .headers , dict ):
1189+ key_value_tuples = response .headers .items ()
1190+ for key , value in key_value_tuples :
11551191 if key .lower () == "set-cookie" :
1156- parsed_cookie = Cookie .SimpleCookie (value )
1157- for cookie in parsed_cookie .values ():
1158- self .cookies [cookie .key ] = cookie .coded_value
1192+ parse_cookies (value , self .cookies )
1193+
11591194 return response
11601195
11611196
0 commit comments