o
    ɶd                     @   s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlmZmZmZ d dlmZ ddlmZmZmZ d dlmZ d dlmZ d dlZd d	lmZ dd
lm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/ d dlm0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7 e6dZ8dZ9dZ:ej;<e9Z=d>e3Z?e	@dZAe	@dZBdZCdZDej;<ddZEeFeEejGreEH dkrdZDdd ZIdAd!d"ZJd#d$ ZKd%d& ZLd'd( ZMd)ZNd*ZOd+ZPd,ZQdd-d.d/d0d1ZRd2d3 ZSd4d5 ZTd6d7 ZUG d8d9 d9eZVG d:d; d;ejWjXZYG d<d= d=ejZZ[eDr7e[ej\j]d>< G d?d@ d@e^Z_dS )B    )absolute_importN)datedatetimetimezone)default_timer   )requestssixurllib3)parse)tz)HTTPResponse)	constants
exceptionsregionsretry)signers)get_config_value_or_defaultvalidate_config)Request)Response)CircuitBreakerStrategyNoCircuitBreakerStrategy)CircuitBreakerCircuitBreakerMonitor)__version__)NONE_SENTINELSentinelextract_service_endpointZMissingZOCI_SDK_APPEND_USER_AGENT4OCI_REALM_SPECIFIC_SERVICE_ENDPOINT_TEMPLATE_ENABLEDzOracle-PythonSDK/{}zdict\(str, (.+?)\)$zlist\[(.+?)\]$zOhttps://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdk_troubleshooting.htmTZOCI_PYSDK_USING_EXPECT_HEADERfalseFc                  G   s   i }| D ]}| | q|S N)update)Zdictionariesmerged
dictionary r%   3usr/lib/python3.10/site-packages/oci/base_client.pymerge_type_mappings8   s   r'    c                 C   s@   d tt t t | pd}| }tr|d t7 }|S )Nz{} (python {}; {}-{}) {}r(   z {})format	USER_INFOplatformpython_versionmachinesystemstripAPPEND_USER_AGENT)extraZagentr%   r%   r&   build_user_agent?   s   r2   c                   C   s   dt t  d S )N z: )strr   utcnowr%   r%   r%   r&   utc_nowM   s   r6   c                 C   s$   | r
dt jjj_d S dt jjj_d S )Nr   r   )r	   movesZhttp_clientZHTTPConnection
debuglevel)
is_enabledr%   r%   r&   is_http_log_enabledQ   s   r:   c                 C   s:   t | D ]\}}t|t jst|trt|| |< q| S r!   )r	   	iteritems
isinstanceinteger_typesfloatr4   )headersheader_nameZheader_valuer%   r%   r&   _sanitize_headers_for_requestsX   s
   rA   streambytesg      $@g      N@,	r3   |)multicsvZtsvZssvZpipesc                 C   s$   d }|dkr|   }|dksd S d S )N   
)readline)fpcurrentr%   r%   r&   _read_all_headersx   s   rM   c                 C   sD   g }| D ]}t |tjr||d q|| qd|}|S )Nzutf-8rI   )r<   r	   	text_typeappendencodejoin)Zinput_bufferZbytes_bufferchunkmsgr%   r%   r&   	_to_bytes~   s   
rT   c                 C   s2   |  d d}t|dko|d do|d dkS )N      r      HTTP/r   s   100)splitlen
startswith)linepartsr%   r%   r&   _is_100_continue   s   
r]   c                   @   s   e Zd Zdd Zdd ZdS )OCIHTTPResponsec                 O   s(   | d| _tj| g|R i | d S )Nstatus_tuple)pop_status_tupler   __init__selfargskwargsr%   r%   r&   rb      s   zOCIHTTPResponse.__init__c                 C   s$   | j d ur| j }d | _ |S t| S r!   )ra   r   _read_status)rd   r_   r%   r%   r&   rg      s
   

zOCIHTTPResponse._read_statusN)__name__
__module____qualname__rb   rg   r%   r%   r%   r&   r^      s    r^   c                       sR   e Zd ZdZ fddZ fddZdddZd	d
 Zdd Z fddZ	  Z
S )OCIConnectionz+ HTTPConnection with 100 Continue support. c                    sF   t t| j|i | | j| _d| _d| _td	t
t| | _d S )NF{}.{})superrk   rb   response_class_original_response_cls_response_received_using_expect_headerlogging	getLoggerr)   rh   idloggerrc   	__class__r%   r&   rb      s
   zOCIConnection.__init__c                    s~   d| _ |dddkr| jdkrtd d| _n| jdkr!td d| _| j| _tt| j	||||g|R i |}d| _
|S )	NFexpectr(   z100-continuer   zUsing Expect header...TzNot using Expect header...)rp   getr8   printrq   ro   rn   rm   rk   _send_requestZ_expect_header_set)rd   methodurlbodyr?   re   rf   Zrvalrv   r%   r&   r{      s$   


zOCIConnection._send_requestNc                 O   s   | j d t| j }| j d d = | jst|tr||7 }d }| | | jr?| jdkr0td t	j
| jdr?| | d S |d urS| jdkrLtd | | d S d S )N)    r   r   z.Waiting 3 seconds for 100-continue response...rV   zBTimeout waiting for 100-continue response, sending message body...)_bufferextendrT   rq   r<   rC   sendr8   rz   r
   utilZwait_for_readsock_handle_expect_response)rd   message_bodyre   rf   rS   r%   r%   r&   _send_output   s&   





zOCIConnection._send_outputc                 C   s  | j dd}z|| }|d d}| jdkrt| t|r2| jdkr(td t| | | nDt	|dkro|d 
dr}| jdkrHtd |d dt|d	 |d df}tjt|d
}|| _d| _W |  d S W |  d S W |  d S W |  d S |  w )Nrbr   rU   z7Received 100-continue response, sending message body...rV   rW   z4Received non-100-continue response, abort request...asciir   )r_   T)r   makefilerJ   rX   r8   rz   r]   rM   _send_message_bodyrY   rZ   decodeint	functoolspartialr^   rn   rp   close)rd   r   rK   r[   r\   r_   rn   r%   r%   r&   r      s:   




z%OCIConnection._handle_expect_responsec                 C   s   |d ur|  | d S d S r!   )r   )rd   r   r%   r%   r&   r      s   z OCIConnection._send_message_bodyc                    s   | j rd S tt| |S r!   )rp   rm   rk   r   )rd   r4   rv   r%   r&   r      s   zOCIConnection.sendr!   )rh   ri   rj   __doc__rb   r{   r   r   r   r   __classcell__r%   r%   rv   r&   rk      s    
rk   c                   @   s   e Zd ZeZdS )OCIConnectionPoolN)rh   ri   rj   rk   ZConnectionClsr%   r%   r%   r&   r      s    r   httpsc                
   @   s  e Zd Zeeejeee	e
dZdZdd Zdd Zedd Zejd	d Zd
d Zdd Zedd Zejdd Zedd Zejdd Zdd Zdddddddddg f
ddZdd Zdd Zdd Zd d! ZdOd"d#Zd$d% ZdPd'd(Zed)d* Z d+d, Z!dQd-d.Z"d/d0 Z#d1d2 Z$d3d4 Z%d5d6 Z&dRd7d8Z'dRd9d:Z(dSd;d<Z)dSd=d>Z*d?d@ Z+dAdB Z,dCdD Z-dEdF Z.dGdH Z/edIdJ Z0dKdL Z1dMdN Z2dS )T
BaseClient)r   r>   r4   boolr   r   objectFc           	      K   s  t ||d || _|| _|dd| _d | _|d| _|d| _|d| _|d| _	|d| _
|d	| _| jrz|d
rI|d
| _nAd }d|v rY|d rY|d}nt|dra|j}| || j| j}tj||||d| j	d| _n|d
std|d
| _|| _|| _t| j|| _t | _d|v r|dnttf| _tt |d| _!t"#d$t%t&| | _'| j'(t")  t |drd| j'_*| j'+t"j, t-d nd| j'_*t-d |d| _.|d| _/d | _0| j/d u st1| j/t2r| j'3d n=t1| j/t4st5d| j/j6d u rt7t89 n| j/j6| _0t:| j0}|d u r<t;| j/j<| j/j=| j/j>| j0d}|| j?| _?| j'3d$| j d S )N)signerregional_clientT	base_pathservice_endpoint_template#service_endpoint_template_per_realmendpoint_service_nameallow_control_chars5client_level_realm_specific_endpoint_template_enabledZservice_endpointregionendpointr   r   r   r   z>An endpoint must be provided for a non-regional service clienttimeoutZadditional_user_agentrl   Zlog_requestsFskip_deserializationcircuit_breaker_strategyz$No circuit breaker strategy enabled!z!Invalid Circuit Breaker Strategy!)failure_thresholdrecovery_timeoutexpected_exceptionnamezEndpoint: {})@r   r   configry   r   	_endpoint
_base_pathr   r   r   _allow_control_chars6_client_level_realm_specific_endpoint_template_enabledr   hasattrr    handle_service_endpoint_templater   endpoint_forr   Z/MissingEndpointForNonRegionalServiceClientErrorservicecomplex_type_mappingsr'   primitive_type_maptype_mappingsr   ZSessionsessionDEFAULT_CONNECTION_TIMEOUTDEFAULT_READ_TIMEOUTr   r2   r   
user_agentrr   rs   r)   rh   rt   ru   
addHandlerNullHandlerdisabledsetLevelDEBUGr:   r   r   circuit_breaker_namer<   r   debugr   	TypeErrorr   r4   uuiduuid4r   r   r   r   r   request)	rd   r   r   r   Ztype_mappingrf   region_to_useZendpoint_templatecircuit_breakerr%   r%   r&   rb     s|   







$
zBaseClient.__init__c                 C   s4   |   }|r|tjv rtj| }||v r|| S |S r!   )should_allow_template_per_realmr   ZREGION_REALMS)rd   Z	region_idr   r   Zshould_enable_realm_templaterealmr%   r%   r&   r   e  s   

z+BaseClient.handle_service_endpoint_templatec                 C      | j S r!   )r   rd   r%   r%   r&   r   p     zBaseClient.endpointc                 C   sV   | j dkr
|| _d S | j r&|| j s&|d| j s&d|| j | _d S || _d S )N/z{}/z{}{})r   r   endswithr)   )rd   r   r%   r%   r&   r   t  s
   

$
c                 C   s
   t | jS r!   )r   r   r   r%   r%   r&   get_endpoint  s   
zBaseClient.get_endpointc                 C   s<   | j r| || j| j}tj| j||| jd| _d S t	d)N)r   r   r   zeSetting the region is not allowed for non-regional service clients. You must instead set the endpoint)
r   r   r   r   r   r   r   r   r   r   )rd   r   r   r%   r%   r&   
set_region  s   zBaseClient.set_regionc                 C   r   r!   r   r   r%   r%   r&   r     r   zBaseClient.allow_control_charsc                 C   s
   || _ d S r!   r   )rd   r   r%   r%   r&   r     s   
c                 C   r   r!   )r   r   r%   r%   r&   r     r   z@BaseClient.client_level_realm_specific_endpoint_template_enabledc                 C   sx   || _ d }d| jv r| jd r| jd}n
t| jdr | jj}| || j| j}t	j
| j||| jd| jd| _d S )Nr   r   r   )r   r   ry   r   r   r   r   r   r   r   r   r   r   r   )rd   r   r   r   r%   r%   r&   r     s   
c                 C   s@   t | jtjst | jtjst | jtjst | jtjrdS dS NTF)r<   r   r   Z%InstancePrincipalsSecurityTokenSignerZ"ResourcePrincipalsFederationSignerZ EphemeralResourcePrincipalSignerZ#EphemeralResourcePrincipalV21Signerr   r%   r%   r&   2is_instance_principal_or_resource_principal_signer  s   z=BaseClient.is_instance_principal_or_resource_principal_signerNTc              
   C   s  |r#t r
| dvrdd |D }d|v r||dd | |}|p&i }t|}t|tj< | j	|tj
< |tjttu rF|  |tj< tjd}|rR||d< |ry| |}| D ]\}}tjjjt| |}|d| d	 |}q]|r| |}|dur|d
dkr| |}t|}| |||}|| }t|||||||d}|  rd}|dk rz	| ||	|
|W S  t j!y } z|d7 }|j"dkr|dk r| j#$  n W Y d}~nd}~ww |dk sdS dS t% }| ||	|
|}t% }| j&'d(t||  |S )a5  
        Makes the HTTP request and return the deserialized data.

        :param resource_path: Path to the resource (e.g. /instance)
        :param method: HTTP method
        :param path_params: (optional) Path parameters in the url.
        :param query_params: (optional) Query parameters in the url.
        :param header_params: (optional) Request header params.
        :param body: (optional) Request body.
        :param response_type: (optional) Response data type.
        :param enforce_content_headers: (optional) Whether content headers should be added for
            PUT and POST requests when not present.  Defaults to True.
        :param allow_control_chars: (optional) Boolean that allows whether or not the response object can contain control chars
        :param operation_name: (optional) String that represents the operational name of the API call.
        :param api_reference_link: (optional) String that represents the link to the API reference page for this operation.
        :return: A Response object, or throw in the case of an error.

        )putpostpatchc                 S   s   i | ]}|  |qS r%   )lower.0kr%   r%   r&   
<dictcomp>      z'BaseClient.call_api.<locals>.<dictcomp>rx   NZOCI_DB_OPC_HOST_SERIALzopc-host-serial{}zcontent-typezapplication/json)r|   r}   query_paramsheader_paramsr~   response_typeenforce_content_headersr   rU   r   i  ztime elapsed for request: {}))enable_expect_headerr   r`   ry   sanitize_for_serializationrA   r*   r   ZHEADER_CLIENT_INFOr   ZHEADER_USER_AGENTHEADER_REQUEST_IDmissingbuild_request_idosenvironitemsr	   r7   urllibr   quoter4   to_path_valuereplaceprocess_query_paramsjsondumps!handle_service_params_in_endpointr   r   r   r   ServiceErrorstatusr   Zrefresh_security_tokentimerru   r   r)   )rd   resource_pathr|   path_paramsr   r   r~   r   r   r   operation_nameapi_reference_linkrequired_argumentsZ/map_lowercase_header_params_keys_to_actual_keysZopc_host_serialr   vreplacementr   r}   r   Zcall_attemptsestartresponseendr%   r%   r&   call_api  sr   







zBaseClient.call_apic              	   C   s   i }t td d|dddd}|D ]L}d}d|v r-d}|d}	|d|	 }||v rW||v s9||v rW||v rA|| n|| }
|rR|
d7 }
|
||d < q|
||< q|r`d||d < qd||< q|S )	Nr(   .r   r   Fz+DotTr   )setfilterrQ   r   rX   find)rd   service_params_urlr   r   r   service_params_mapZservice_paramsservice_paramZshould_append_dotZdot_idxvaluer%   r%   r&   map_service_params_to_values  s$   (


z'BaseClient.map_service_params_to_valuesc                 C   sr   | j }td}|| dkr7|d}|||d  }| ||||}| D ]\}	}
d|	 d }	||	|
}q&|S )Nzhttps://r   r   r   )r   rY   rfindr	  r   r   )rd   r   r   r   r   Z	start_idxZend_idxr  r  r  r  r%   r%   r&   r   2  s   
z,BaseClient.handle_service_params_in_endpointc                 C   sF   |t u rt S |tvrtd|tt |dkr|S t| |S )Nz6Invalid collection format type {}. Valid types are: {}rG   )r   VALID_COLLECTION_FORMAT_TYPES
ValueErrorr)   listkeysrQ   )rd   param_valueZcollection_format_typer%   r%   r&    generate_collection_format_param@  s   z+BaseClient.generate_collection_format_paramc                 C   s   |  |}i }| D ]?\}}t|tr|rdnd||< qt|ts/t|ts/| |||< qt|tr9|||< q| D ]\}}||d||< q=q|S )Ntruer    rl   )r   r   r<   r   dictr  r   r)   )rd   r   Zprocessed_query_paramsr   r   Z	inner_keyZ	inner_valr%   r%   r&   r   L  s   



zBaseClient.process_query_paramsc                 C   s~  | j t dt|j|jf   d }| jr+t| jj	}|t
jkr+| j d| | j}|js4|j}d}|jtkr=d}zLt }| jj|j|j||j|j|j|| jd}	t }
|jtj rs| j t d|jtj t|
|   |	rt|	dr| j t d t|	j  W nY tjj y } z|j!sd	|_!|j!d
|j d |j dt" f |_!t |d }~w tjj#y } z|j!sd	|_!|j!d
|j d |j dt" f |_!t#|d }~ww |j}| j t dt|	j$   d|	j$  krdksn | j%}|jd |j }t&}t'(t)j*+ }| ,|	|\}}}|	j$dkrI|dkrI| j -d| |	j.}|	/  t00| j}| j/  || _t1| j2t3r| j24|	j$|rt| jj	}||kro| j -d|| | 5||	||||||||| n| 6||	||||||||| |r|	}n|t7kr|	j.}n|r| 8|	j.||}nd }t9|	j$|	j:||}| j t d  |S )NzRequest: %s %szCircuit Breaker State is {}!FT)authparamsr?   datarB   r   ztime elapsed for request {}: {}elapsedztime elapsed in response: r(   zRequest Endpoint: r3   zd See {} for help troubleshooting this error, or contact support and provide this full error message.zResponse status: %s   i+  i  ZRequestEntityTooLargez?Recieved a 413/RequestEntityTooLarge from {}, resetting sessionz+Circuit Breaker state changed from {} to {}zResponse returned);ru   infor6   r4   r|   r}   r   r   ry   statecircuitbreakerZSTATE_CLOSEDr   r)   r   r   Zwithout_content_headersr   STREAM_RESPONSE_TYPEr   r   r   r   r   r~   r   r   r   r   r  r   r   ZConnectTimeoutre   TROUBLESHOOT_URLZRequestExceptionstatus_coder   r*   r   nowr   utc	isoformat)get_deserialized_service_code_and_messagewarningcontentr   copyr<   r   r   Zis_transient_errorraise_transient_service_errorraise_service_errorBYTES_RESPONSE_TYPEdeserialize_response_datar   r?   )rd   r   r   r   r   Zinitial_circuit_breaker_stater   rB   r   r   r   r   r   target_servicerequest_endpointclient_version	timestampservice_codemessagedeserialized_data_Znew_sessionZnew_circuit_breaker_stateZrespr%   r%   r&   r     s   "

	*(
(

 
 
zBaseClient.requestc                 C   s   t t dd S )N-r(   )r4   r   r   r   upperr   r%   r%   r&   r     s   zBaseClient.build_request_id   c                 C   s,   d|vrd dd t|D |d< d S d S )Nzopc-retry-tokenr(   c                 s   s&    | ]}t  tjtj V  qd S r!   )randomSystemRandomchoicestringascii_lettersdigits)r   r1  r%   r%   r&   	<genexpr>  s   $ z;BaseClient.add_opc_retry_token_if_needed.<locals>.<genexpr>)rQ   range)rd   r   Zretry_token_lengthr%   r%   r&   add_opc_retry_token_if_needed  s    z(BaseClient.add_opc_retry_token_if_neededc                 C   s   d| vr
d| d< d S d S )Nzopc-client-retriesr  r%   )r   r%   r%   r&   add_opc_client_retries_header  s   z(BaseClient.add_opc_client_retries_headerc                 C   s   t |tkrd|S t|S )z
        Takes value and turn it into a string suitable for inclusion in
        the path, by url-encoding.

        :param obj: object or string value.

        :return string: quoted value.
        rD   )typer  rQ   r4   rd   objr%   r%   r&   r     s   	
zBaseClient.to_path_valuec                    sl  t jt jtttdf}t jttt jftt jfd} rusu dr2tt	s2
  nC drIttsIttsI
  n, jv rctt	sbtj  sb
  n |v rut|  su
  t|r|S tu rdS ttsttr fddD S ttrjstjtj ddS ttr S tt	rԈ}d} rӈ fd	d
|D }n,tdstdttjfdd
j D }fdd
t  jD }i }t  |D ],\}	}
d}|	}|r||	 d }||	 d }r'd|n|}!|
||||	< q|S )a  
        Builds a JSON POST object.

        If obj is str, int, float, bool, None, return directly.
        If obj is datetime.datetime, datetime.date
            convert to string in iso8601 format.
        If obj is list, sanitize each element in the list.
        If obj is dict, return the dict.
        If obj is swagger model, return the properties dict.

        :param obj: The data to serialize.
        :return: The serialized form of data.
        N)r4   r   r   r>   dict(list[c                    s4   g | ]} | r nd rd nd qS )Nz[*])r   (extract_list_item_type_from_swagger_type)r   Zsub_obj)declared_type
field_namerd   r%   r&   
<listcomp>%  s    z9BaseClient.sanitize_for_serialization.<locals>.<listcomp>z+00:00Zc                    s   i | ]}| |fqS r%   r%   r   )dict_value_typer%   r&   r   9  r   z9BaseClient.sanitize_for_serialization.<locals>.<dictcomp>swagger_typesz7Not able to serialize data: {} of type: {} in field: {}c                    s0   i | ]\}}t  |d ur j| t  |qS r!   )getattrattribute_map)r   attrr1  rA  r%   r&   r   ?  s
    c                    s    i | ]\}} j | ||fqS r%   )rL  )r   rM  swagger_typerN  r%   r&   r   C  s     r   r   rl   )"r	   string_typesr=   r>   r   r?  is_none_or_none_sentinelrZ   r<   r  "raise_type_error_serializing_modelr  tupler   r   r   tzinfopytzr   localize
astimezoner!  r   r   )extract_dict_value_type_from_swagger_typer   r   r)   r4   rh   rJ  r   r;   r   )rd   rA  rE  rF  typesZ0declared_swagger_type_to_acceptable_python_typesobj_dictZkeys_to_types_and_field_nameZsanitized_dictkeyvalZvalue_declared_typeZinner_field_namer%   )rE  rI  rF  rA  rd   r&   r     sl   	







z%BaseClient.sanitize_for_serializationc                 C   s   |d u p|t u S r!   )r   r@  r%   r%   r&   rQ  R  s   z#BaseClient.is_none_or_none_sentinelc                 C   s   t d|t||t|j)NzGField {} with value {} was expected to be of type {} but was of type {})r   r)   r4   r?  rh   )rd   rF  rA  rE  r%   r%   r&   rR  U  s   z-BaseClient.raise_type_error_serializing_modelc                 C       t |}d }|r|d}|S Nr   )DICT_VALUE_TYPE_REGEXsearchgrouprd   rO  mresultr%   r%   r&   rX  X  
   

z4BaseClient.extract_dict_value_type_from_swagger_typec                 C   r]  r^  )LIST_ITEM_TYPE_REGEXr`  ra  rb  r%   r%   r&   rD  a  re  z3BaseClient.extract_list_item_type_from_swagger_typec                 C   &   t j|j||j|||||||	|
|dN)Zoriginal_requestr   r   r*  r+  r,  r-  r0  )r   r   r  r?   rd   r   r   r.  r/  r   r   r*  r+  r,  r-  r0  r%   r%   r&   r'  j     zBaseClient.raise_service_errorc                 C   rg  rh  )r   ZTransientServiceErrorr  r?   ri  r%   r%   r&   r&  y  rj  z(BaseClient.raise_transient_service_errorc                 C   sF   |  |jd|}d }d }t|tr|d}|d}n|}|||fS )Nr   coder/  )r)  r$  r<   r  ry   )rd   r   r   r0  r.  r/  r%   r%   r&   r"    s   


z4BaseClient.get_deserialized_service_code_and_messagec           	      C   s   | d}z| |}tj|| d}|dkst|tjkr |}W n	 ty*   Y nw | jr0|S t	 }| 
||}t	 }| jt dt||   |S )ai  
        Deserializes response into an object.

        :param response_data: object to be deserialized.
        :param response_type: class literal for
            deserialized object, or string of class name.
        :param allow_control_chars: boolean to allow control character in a response. Defaults to None

        :return: deserialized object.
        utf8)strictr4   z-python SDK time elapsed for deserializing: {})r   should_allow_control_charsr   loadsr?  r	   rN   r  r   r   _BaseClient__deserializeru   r   r6   r)   r4   )	rd   Zresponse_datar   r   rn  Zjson_responser   resr   r%   r%   r&   r)    s"   


 z$BaseClient.deserialize_response_datac                    s
  |du rdS | drtd|d fdd|D S | dr8td|d	 fd
d| D S | jv rC j| }n ||S t|drX||} j| }|t	t
tjtfv rg ||S |tkrm|S |tkrv |S |tkr |S  ||S )z
        Deserialize a dict, list, or str into an object.

        :param data: dict, list or str
        :param cls: string of class name

        :return: object.
        NrC  zlist\[(.*)\]r   c                    s   g | ]}  |qS r%   rp  )r   Zsub_datard   Zsub_klsr%   r&   rG    s    z,BaseClient.__deserialize.<locals>.<listcomp>rB  zdict\(([^,]*), (.*)\)rU   c                    s   i | ]\}}|  |qS r%   rr  )r   r   r   rs  r%   r&   r     s    z,BaseClient.__deserialize.<locals>.<dictcomp>get_subtype)rZ   rematchra  r   r   "_BaseClient__deserialize_primitiver   rt  r   r>   r	   ur   r   r   _BaseClient__deserialize_dater   !_BaseClient__deserialize_datetime_BaseClient__deserialize_model)rd   r  clsr%   rs  r&   Z__deserialize  s6   	







zBaseClient.__deserializec                 C   sD   z||}W |S  t y   t|}Y |S  ty!   |}Y |S w )z
        Deserializes string to primitive type.

        :param data: str.
        :param cls: class literal.

        :return: int, float, str, bool.
        )UnicodeEncodeErrorr	   rx  r   )rd   r  r|  r  r%   r%   r&   Z__deserialize_primitive  s   	
z"BaseClient.__deserialize_primitivec                 C   s@   zt | W S  ty   | Y S  ty   td|w )zb
        Deserializes string to date.

        :param string: str.
        :return: date.
        z(Failed to parse `{0}` into a date object)r   r   ImportErrorr  	Exceptionr)   )rd   r8  r%   r%   r&   Z__deserialize_date  s   zBaseClient.__deserialize_datec                 C   s   zt |d}|jt d}|W S  ty:   zt|W  Y S  ty,   | Y  Y S  ty9   td	|w  tyD   | Y S w )z
        Deserializes string to datetime.

        The string should be in iso8601 datetime format.

        :param string: str.
        :return: datetime.
        z%Y-%m-%dT%H:%M:%S.%fZ)rT  z,Failed to parse `{0}` into a datetime object)
r   strptimer   r   Ztzutcr  r   r~  r  r)   )rd   r8  ZnaivedatetimeZawaredatetimer%   r%   r&   Z__deserialize_datetime  s   	z!BaseClient.__deserialize_datetimec                 C   sL   | }|j  D ]\}}|j| }||v r#|| }t||| || q|S )z
        Deserializes list or dict to model.

        :param data: dict, list.
        :param cls: class literal.
        :return: model object.
        )rJ  r   rL  setattrrp  )rd   r  r|  instancerM  Z	attr_typepropertyr  r%   r%   r&   Z__deserialize_model'  s   
zBaseClient.__deserialize_modelc                 C   s,   d}| r| }|S |r|}|S t jrt j}|S )a  
        Gets the preferred Retry Strategy for the client
        :param operation_retry_strategy: (optional) Operation level Retry Strategy
        :param client_retry_strategy: (optional) Client level Retry Strategy
        :return: Preferred Retry Strategy.
        N)r   ZGLOBAL_RETRY_STRATEGY)Zoperation_retry_strategyZclient_retry_strategyZretry_strategyr%   r%   r&   get_preferred_retry_strategy9  s   z'BaseClient.get_preferred_retry_strategyc                 C   s8   |}| j }tj}|d ur|S |d ur|S |du rdS dS r   )r   r   ALLOW_CONTROL_CHARACTERS)rd   r   Zrequest_configurationclient_configurationZglobal_configurationr%   r%   r&   rn  J  s   z%BaseClient.should_allow_control_charsc                 C   s6   | j }tjt}|dur|S |dur| dkS dS )z
        Returns a boolean of whether or not we should use realm specific endpoint templates

        The highest precedence goes in decending order. The order: Client / Environment / Default (False)
        Nr  F)r   r   r   ry   r   r   )rd   r  Zenv_configurationr%   r%   r&   r   ]  s   z*BaseClient.should_allow_template_per_realm)NNN)r4  )NN)NNNNNNNr!   )3rh   ri   rj   r   r>   r	   rx  r   r   r   r   r   r  rb   r   r  r   setterr   r   r   r   r   r   r	  r   r  r   r   r   r=  staticmethodr>  r   r   rQ  rR  rX  rD  r'  r&  r"  r)  rp  rw  ry  rz  r{  r  rn  r   r%   r%   r%   r&   r      s    
Z







e
>V


X	
	


*,
r   r  )`
__future__r   r   rr   r+   r  rU  r5  r   ru  r8  r   r%  Z	_strptimer   r   r   Ztimeitr   r   _vendorr   r	   r
   Zdateutil.parserr   Zdateutilr   r   Zsix.moves.http_clientr   r(   r   r   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   versionr   r   r   r   r   r   ZAPPEND_USER_AGENT_ENV_VAR_NAMEr   r   ry   r0   r)   r*   compiler_  rf  r  r   Zexpect_header_env_varr<   rP  r   r'   r2   r6   r:   rA   r  r(  r   r   r  rM   rT   r]   r^   Z
connectionZVerifiedHTTPSConnectionrk   ZHTTPSConnectionPoolr   ZpoolmanagerZpool_classes_by_schemer   r   r%   r%   r%   r&   <module>   s   




		T