44library, it is not recommened and could possible result in some strange
55behavior.
66"""
7- import sys
87import time
98import locale
109import logging
1110import threading
1211from datetime import datetime
13- try :
14- import json
15- except ImportError :
16- try :
17- import simplejson as json
18- except ImportError :
19- sys .exit ('Could not find json or simplejson libraries.' )
20- if sys .version_info [0 ] == 2 :
21- from httplib import HTTPConnection , HTTPSConnection , HTTPException
22- elif sys .version_info [0 ] == 3 :
23- from http .client import HTTPConnection , HTTPSConnection , HTTPException
24- # API Libs
25- from dyn import __version__
12+
13+ from . import __version__
14+ from .compat import (HTTPConnection , HTTPSConnection , HTTPException , json ,
15+ is_py2 , is_py3 , prepare_to_send , force_unicode )
2616
2717
2818def cleared_class_dict (dict_obj ):
@@ -107,7 +97,7 @@ def close_session(cls):
10797 key = getattr (cls , '__metakey__' )
10898 closed = cls ._instances .get (key , {}).pop (cur_thread , None )
10999 if len (cls ._instances .get (key , {})) == 0 :
110- del cls ._instances [ key ]
100+ cls ._instances . pop ( key , None )
111101 return closed
112102
113103 @property
@@ -164,11 +154,7 @@ def _handle_response(self, response, uri, method, raw_args, final):
164154 if self .poll_incomplete :
165155 response , body = self .poll_response (response , body )
166156 self ._last_response = response
167- ret_val = None
168- if sys .version_info [0 ] == 2 :
169- ret_val = json .loads (body )
170- elif sys .version_info [0 ] == 3 :
171- ret_val = json .loads (body .decode ('UTF-8' ))
157+ ret_val = json .loads (body .decode ('UTF-8' ))
172158
173159 self ._meta_update (uri , method , ret_val )
174160 # Handle retrying if ZoneProp is blocking the current task
@@ -225,15 +211,24 @@ def execute(self, uri, method, args=None, final=False):
225211 :param final: boolean flag representing whether or not we have already
226212 failed executing once or not
227213 """
214+ if self ._conn is None :
215+ self .connect ()
216+
228217 uri = self ._validate_uri (uri )
229218
230219 # Make sure the method is valid
231220 self ._validate_method (method )
232221
233- self .logger .debug ('uri: {}, method: {}, args: {}' .format (uri , method ,
234- args ))
235222 # Prepare arguments to send to API
236223 raw_args , args , uri = self ._prepare_arguments (args , method , uri )
224+
225+ # Don't display password when debug logging
226+ cleaned_args = json .loads (args )
227+ if 'password' in cleaned_args :
228+ cleaned_args ['password' ] = '*****'
229+
230+ self .logger .debug ('uri: {}, method: {}, args: {}' .format (uri , method ,
231+ cleaned_args ))
237232 # Send the command and deal with results
238233 self .send_command (uri , method , args )
239234
@@ -314,11 +309,7 @@ def send_command(self, uri, method, args):
314309 self ._conn .putheader ('Content-length' , '%d' % len (args ))
315310 self ._conn .endheaders ()
316311
317- if sys .version_info [0 ] == 2 :
318- self ._conn .send (bytes (args ))
319- elif sys .version_info [0 ] == 3 :
320- # noinspection PyArgumentList
321- self ._conn .send (bytes (args , 'UTF-8' ))
312+ self ._conn .send (prepare_to_send (args ))
322313
323314 def wait_for_job_to_complete (self , job_id , timeout = 120 ):
324315 """When a response comes back with a status of "incomplete" we need to
@@ -343,7 +334,27 @@ def wait_for_job_to_complete(self, job_id, timeout=120):
343334 response = self .execute (uri , 'GET' , api_args )
344335 return response
345336
337+ def __getstate__ (cls ):
338+ """Because HTTP/HTTPS connections are not serializeable, we need to
339+ strip the connection instance out before we ship the pickled data
340+ """
341+ d = cls .__dict__ .copy ()
342+ d .pop ('_conn' )
343+ return d
344+
345+ def __setstate__ (cls , state ):
346+ """Because the HTTP/HTTPS connection was stripped out in __getstate__ we
347+ must manually re-enter it as None and let the sessions execute method
348+ handle rebuilding it later
349+ """
350+ cls .__dict__ = state
351+ cls .__dict__ ['_conn' ] = None
352+
346353 def __str__ (self ):
347354 """str override"""
348- return '<{}>' .format (self .name )
355+ return force_unicode ( '<{}>' ) .format (self .name )
349356 __repr__ = __unicode__ = __str__
357+
358+ def __bytes__ (self ):
359+ """bytes override"""
360+ return bytes (self .__str__ ())
0 commit comments