o
    #ju                    @   s  d 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 ddl
mZ ddlmZmZmZ ddlmZmZmZmZ ddlZddlZddlZddlZddlmZ ddlmZ dd	lmZ dd
lmZ ddl m!Z! ddl m"Z" ddl m#Z# ddl$m%Z% ddl$m&Z& ddl$m'Z' ddl$m(Z( ddl$m)Z) ddl*m+Z+ ddl,m-Z- ddl,m.Z. ddl/m0Z0 ddlm1Z1 ddl2m3Z4 e5e6Z7dZ8dZ9dZ:dZ;G dd dZ<G dd deZ=G d d! d!e>Z?G d"d# d#e>Z@dS )$z.
This module provides a client class for BOS.
    N)str)bytes)	iteritemsiterkeys
itervalues)ThreadPoolExecutorwaitALL_COMPLETEDFIRST_COMPLETED)bce_client_configuration)utils)bce_v1_signer)BceBaseClient)BceClientError)BceServerError)BceHttpClientError)bce_http_client)handler)http_content_types)http_headers)http_methods)bos)bos_handler)storage_class)required)compats   syncs   asyncZAES256s   httpc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	UploadTaskHandlez?
    handle to control multi upload file with multi-thread
    c                 C   s   d| _ t | _d S NF)cancel_flag	threadingLockcancel_lockself r$   a/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/baidubce/services/bos/bos_client.py__init__C   s   zUploadTaskHandle.__init__c                 C   s   | j   d| _| j   dS )zI
        cancel putting super object from file with multi-thread
        TNr!   acquirer   releaser"   r$   r$   r%   cancelG   s   
zUploadTaskHandle.cancelc                 C   s   | j   | j}| j   |S )z!
        get cancel flag
        r'   )r#   resultr$   r$   r%   	is_cancelO   s   

zUploadTaskHandle.is_cancelN)__name__
__module____qualname____doc__r&   r*   r,   r$   r$   r$   r%   r   ?   s
    r   c                
   @   s  e Zd ZdZdddZdddZeeefdddd	Z	eeefddddZ
eeefddddZeeefddddZedd ZeeefeefddddZeeefefddddZeeefeefddddZeeefddddZeeefddddZeeefdd d d!Zeeefddd"d#Zeeefddd$d%Zeeefdedfd&d'Zeeefddd(d)Zeeefddd*d+Zeeefefd,dd-d.Zeeefddd/d0Zeeefddd1d2Zeeefefd3dd4d5Z eeefdd!d6d7Z!eeefdd!d8d9Z"eeefdd!d:d;Z#eeefddd<d=Z$eeefefd>dd?d@Z%eeefeefdAddBdCZ&eeefeefdAddDdEZ'eeefdddFdGZ(eeefdd!dHdIZ)eeefdddJdKZ*eeefdddLdMZ+eeefeefdNdOdPddddde,j-fdQdRZ.eeefeefdS	ddTdUZ/eeefdddVdWZ0eeefdddXdYZ1eeefefdZ	dd[d\Z2eeefddd]d^Z3eeefddd_d`Z4eeefd		d"dbdcZ5eeefdd dddeZ6edfdg Z7edhdi Z8eeefeefdN		d#djdkZ9eeefeefdNd$dmdnZ:ed%dpdqZ;edrds Z<eeefeefdNd&dtduZ=eeefeefeefdv		d'dwdxZ>eeefeefdNd dydzZ?eeefeefe@feAjBfd{															d(d|d}ZCeeefeefeefd~														d)ddZDeeefeefe@feAjBfd{																		d*ddZEeeefeefeefd																		d*ddZFeeefeefeefd																			d+ddZGeeefeefeefeefd										d,ddZHeeefeefdNd!ddZIeeefefddddZJeeefeefeefd		d!ddZKeeefddddZLeeefddddZMeeefeefdN				d&ddZNeeefeefeefeOfeAjBfe@fd			d-ddZPeeefeefeefeefeefeOfeAjBfeAjBfd					d#ddZQeeefeefeefeOfeAjBfeefeAjBfd				d-ddZReeefeefeefefd								d.ddZSeeefeefeefddddZTeeefeefeefd		d ddZUeeefeefeefddddZVeeefd			d#ddZWeeefdd ddZX		d'ddZYeeefeefeefdv														d/ddZZeeefeefeefddddZ[eeefeefdN				d&ddZ\eeefeefdNdddZ]eeefeefdNdddZ^eeefeefeefd			d ddZ_eeefeefeefe`fd		d'ddĄZaeeefeefdōdddǄZbeeefeefedȍd!ddʄZcddd̄ZdeeOeOfd͍dddτZedddфZfeeefddddӄZgeeefefdԍdddքZheeefdddd؄ZieeefefdٍdddۄZjeeefdddd݄Zkeeefdddd߄ZleeefeefefddddZmdddZneeefeefdNdddZoeeefeefdNdddZpeeefeefddddZqeeefddddZreeefd		d0ddZseeefeOfd	dddZteeefddddZueeefddddZveeefd	dddZweeefeOfd	dddZxeeefd	dddZyeeefefd	ddd Zzeeefd	dddZ{eeefd	dddZ|eeefefd	dddZ}eeefd	ddd	Z~e																	d1d
dZedd Zed2ddZdd Zed3ddZdd Zdd Zedd Zedd Z			d4ddZdS (5  	BosClientz
    sdk client
    Nc                 C   s   t | | d S N)r   r&   r#   configr$   r$   r%   r&   ]   s   zBosClient.__init__c                 C   s   | j tj|dS )z
        List buckets of user

        :param config: None
        :type config: BceClientConfiguration
        :returns: all buckets owned by the user.
        :rtype: baidubce.bce_response.BceResponse
        r4   _send_requestr   GETr3   r$   r$   r%   list_buckets`   s   	zBosClient.list_buckets)bucket_namec                 C   s"   ddi}| j tj|||d}|jS )a  
        Get the region which the bucket located in.

        :param bucket_name: the name of bucket
        :type bucket_name: string or unicode
        :param config: None
        :type config: BceClientConfiguration

        :return: region of the bucket
        :rtype: str
        s   location    paramsr4   )r7   r   r8   Zlocation_constraint)r#   r:   r4   r=   responser$   r$   r%   get_bucket_locationk   s   zBosClient.get_bucket_locationFc                 C   sP   i }|dur||t j< |rtj|t j< tddi}nd}| jtj	||||dS )a  
        Create bucket with specific name

        :param bucket_name: the name of bucket
        :type bucket_name: string or unicode
        :param config: None
        :type config: BceClientConfiguration
        :returns:
        :rtype: baidubce.bce_response.BceResponse
        NZenableMultiAzT)headersbodyr4   )
r   ZBOS_TAG_LISTr   JSONCONTENT_TYPEjsondumpsr7   r   PUT)r#   r:   Ztag_listZ
enable_mazr4   r@   rA   r$   r$   r%   create_bucket|   s   
zBosClient.create_bucketc              
   C   s~   z| j tj||d W dS  ty> } z&t|jtr8|jjtj	j
kr)W Y d}~dS |jjtj	jkr8W Y d}~dS |d}~ww )z
        Check whether there is a bucket with specific name

        :param bucket_name: None
        :type bucket_name: str
        :return:True or False
        :rtype: bool
        r5   TNF)r7   r   HEADr   
isinstance
last_errorr   status_codehttpclient	FORBIDDEN	NOT_FOUND)r#   r:   r4   er$   r$   r%   does_bucket_exist   s   
zBosClient.does_bucket_existc                 C      | j tj|ddi|dS )z
        Get Access Control Level of bucket

        :type bucket: string
        :param bucket: None
        :return:
            **json text of acl**
           aclr;   r<   r6   r#   r:   r4   r$   r$   r%   get_bucket_acl      
zBosClient.get_bucket_aclc                 C   s.   i }t | jD ]\}}|ds|||< q|S )N_)r   __dict__
startswith)aclr+   kvr$   r$   r%   _dump_acl_object   s   
zBosClient._dump_acl_object)r:   rZ   c                 C   4   | j tj|tjd|itjdtjt	j
iddi|dS )z
        Set Access Control Level of bucket

        :type bucket: string
        :param bucket: None

        :type grant_list: list of grant
        :param grant_list: None
        :return:
            **HttpResponse Class**
        accessControlListdefaultrS   r;   rA   r@   r=   r4   r7   r   rF   rD   rE   r1   r]   r   rC   r   rB   )r#   r:   rZ   r4   r$   r$   r%   set_bucket_acl   s   

zBosClient.set_bucket_acl)r:   
canned_aclc                 C   s    | j tj|tj|iddi|dS )zi

        :param bucket_name:
        :param canned_acl:
        :param config:
        :return:
        rS   r;   r@   r=   r4   )r7   r   rF   r   BCE_ACL)r#   r:   re   r4   r$   r$   r%   set_bucket_canned_acl   s   	zBosClient.set_bucket_canned_acl)r:   r   c                 C   >   t |}| jtj|tjd|itjdt	j
tjiddi|dS )N

        :param bucket_name:
        :param config:
        :return:
        ZstorageClassr`      storageClassr;   rb   r   convert_to_stringr7   r   rF   rD   rE   r1   r]   r   rC   r   rB   )r#   r:   r   r4   r$   r$   r%   set_bucket_storage_class   s   


z"BosClient.set_bucket_storage_classc                 C   rR   )rj   rk   r;   r<   r6   rT   r$   r$   r%   get_bucket_storage_class   s
   z"BosClient.get_bucket_storage_classc                 C   s   | j tj||dS )z
        Delete a Bucket(Must Delete all the Object in Bucket before)

        :type bucket: string
        :param bucket: None
        :return:
            **HttpResponse Class**
        r5   r7   r   DELETErT   r$   r$   r%   delete_bucket
  s   
zBosClient.delete_bucketc                 C   sT   i }|dur
||d< |dur||d< | j tj|tj|tjdtjt	j
iddi|dS )a  
        Set index page and not_found 404 page for static website trusteeship

        :type bucket_name: string
        :param bucket_name: None

        :type index:string
        :param index:object name of index page for static website trusteeship

        :type not_found:string
        :param not_found:object name of not_found 404 page for static website trusteeship

        :return:
            **HttpResponse Class**
        NindexZnotFoundr`      websiter;   rb   rc   )r#   r:   rs   	not_foundr4   rA   r$   r$   r%   put_bucket_static_website  s   
z#BosClient.put_bucket_static_websitec                 C   rR   )z
        Get Information of static website trusteeship

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        rt   r;   r<   r6   rT   r$   r$   r%   get_bucket_static_website5  
   z#BosClient.get_bucket_static_websitec                 C   rR   )z
        Delete Information of static website trusteeship to be closed

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        rt   r;   r<   rp   rT   r$   r$   r%   delete_bucket_static_websiteF  rx   z&BosClient.delete_bucket_static_websitec                 C   ri   )aN  
        Set server encryption for bucket

        :type bucket: string
        :param bucket: None

        :type encryption_algorithm: string
        :param grant_list: server encryption algorithm for bucekt.Now the value of encryption_algorithm
        only is 'AES256'

        :return:
            **HttpResponse Class**
        ZencryptionAlgorithmr`   
   encryptionr;   rb   rl   )r#   r:   Zencryption_algorithmr4   r$   r$   r%   put_bucket_encryptionW  s   


zBosClient.put_bucket_encryptionc                 C   rR   )z
        Get status of server encryption

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        rz   r;   r<   r6   rT   r$   r$   r%   get_bucket_encryptiono  rx   zBosClient.get_bucket_encryptionc                 C   rR   )z
        Close server encryption

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        rz   r;   r<   rp   rT   r$   r$   r%   delete_bucket_encryption  rx   z"BosClient.delete_bucket_encryption)r:   resourcec                 C   r^   )a  
        Open image copyright protection and set resource

        :type bucket: string
        :param bucket: None

        :type resource: list of  string
        :param grant_list: resource range to be protected

        :return:
            **HttpResponse Class**
        r~   r`      copyrightProtectionr;   rb   rc   )r#   r:   r~   r4   r$   r$   r%   put_bucket_copyright_protection  s   

z)BosClient.put_bucket_copyright_protectionc                 C   rR   )z
        Get configuration of image copyright protection

        :type bucket: string
        :param grant_list: None

        :return:
            **HttpResponse Class**
        r   r;   r<   r6   rT   r$   r$   r%   get_bucket_copyright_protection  rx   z)BosClient.get_bucket_copyright_protectionc                 C   rR   )z
        Close image copyright protection

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        r   r;   r<   rp   rT   r$   r$   r%   "delete_bucket_copyright_protection  rx   z,BosClient.delete_bucket_copyright_protection)r:   replicationc                 C   sN   ddi}d|v rt |d |d< | jtj|tj|tjdt	j
tji||dS )a  
        Open cross-region replication

        :type bucket: string
        :param bucket: None

        :type replication: dict
        :type replication: configuration for cross-region replication

        :return:
            **HttpResponse Class**
           replicationr;   id   idr`   rb   r   convert_to_bytesr7   r   rF   rD   rE   r1   r]   r   rC   r   rB   )r#   r:   r   r4   r=   r$   r$   r%   put_bucket_replication  s   
z BosClient.put_bucket_replicationc                 C   2   ddi}|durt ||d< | jtj|||dS )z
        Get configuration of cross-region replication 

        :type bucket: string
        :param bucket: None

        :type id: string
        :param id: replication rule id

        :return:
            **HttpResponse Class**
        r   r;   Nr   r<   r   r   r7   r   r8   r#   r:   r   r4   r=   r$   r$   r%   get_bucket_replication     z BosClient.get_bucket_replicationc                 C   r   )a   
        Delete configuration of cross-region replication and close it 

        :type bucket: string
        :param bucket: None

        :type id: string
        :param id: replication rule id

        :return:
            **HttpResponse Class**
        r   r;   Nr   r<   r   r   r7   r   rq   r   r$   r$   r%   delete_bucket_replication  r   z#BosClient.delete_bucket_replicationc                 C   r   )a1  
        Get status of cross-region replication,for exapmle 'historyReplicationPercent',
        'latestReplicationTime'

        :type bucket: string
        :param bucket: None

        :type id: string
        :param id: replication rule id

        :return:
            **HttpResponse Class**
        s   replicationProgressr;   Nr   r<   r   r   r$   r$   r%   get_bucket_replication_progress  s   z)BosClient.get_bucket_replication_progressc                 C   s   | j tj|ddd|dS )z
        list configuration of cross-region replication rule

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        r;   )r   s   listr<   r6   rT   r$   r$   r%   list_bucket_replication(  s
   z!BosClient.list_bucket_replication)r:   	inventoryc                 C   s@   t |d }| jtj|tj|tjdt	j
tjid|d|dS )z
        set bucket inventoru

        :type bucket: string
        :param bucket: None

        :type inventory: dict
        :param inventory: configuration for bucket inventory

        :return:
            **HttpResponse Class**
        r   r`   r;   	   inventoryr   rb   r   )r#   r:   r   r4   Zconf_idr$   r$   r%   put_bucket_inventory8  s   
zBosClient.put_bucket_inventory)r:   inventory_conf_idc                 C       | j tj|dt|d|dS )z
        Get configuration of bucket inventory

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        r;   r   r<   )r7   r   r8   r   r   r#   r:   r   r4   r$   r$   r%   get_bucket_inventoryO  
   zBosClient.get_bucket_inventoryc                 C   r   )z
        Delete configuration of bucket inventory

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        r;   r   r<   )r7   r   rq   r   r   r   r$   r$   r%   delete_bucket_inventory_  r   z!BosClient.delete_bucket_inventoryc                 C   rR   )z
        list configuration of bucket inventory

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        r   r;   r<   r6   rT   r$   r$   r%   list_bucket_inventoryo  rx   zBosClient.list_bucket_inventoryc                 C   sF   |dur	t |}| jtj|tjd|itjdt	j
tjiddi|dS )z
        Open bucket trash function

        :type bucket: string
        :param bucket: None

        :type trash_dir: string
        :param trash_dir: directory of trash,optional

        :return:
            **HttpResponse Class**
        NZtrashDirr`      trashr;   rb   rl   )r#   r:   Z	trash_dirr4   r$   r$   r%   put_bucket_trash  s   


zBosClient.put_bucket_trashc                 C   rR   )z
        Get status of bucket trash

        :type bucket: string
        :param grant_list: None

        :return:
            **HttpResponse Class**
        r   r;   r<   r6   rT   r$   r$   r%   get_bucket_trash  rx   zBosClient.get_bucket_trashc                 C   rR   )z
        Close bucket trash

        :type bucket: string
        :param bucket: None

        :return:
            **HttpResponse Class**
        r   r;   r<   rp   rT   r$   r$   r%   delete_bucket_trash  rx   zBosClient.delete_bucket_trash)r:   keyr   i  c              
   C   s|  t |}|pdd}t| t| t |}|dkr#td| |	|}	|p,i }|p0i }|durYt	|t
rV| }|dkrGtj|	_n|dkrPtj|	_n	td| ||	_t|	j|	j\}}}|}||jkrt|d	t | 7 }||tj< | |	||}|
tjkr|
tjkrtd
g}|	jdur|	j|tj < t|	j|
|||||||tj  < dt |j!||t"|df S )a  
        Get an authorization url with expire time.
        specified  protocol in endpoint > protocal > default protocol in config.

        :type timestamp: int
        :param timestamp: None

        :type expiration_in_seconds: int
        :param expiration_in_seconds: None

        :type options: dict
        :param options: None

        :param is_official_domain: default use not official domain,example: bucket.bj.bcebos.com

        :return:
            **URL string**
         /s   v1z!generate url the key param error!NrL   httpszInvalid protocol: %s   :s   hosts   %s://%s%s?%sF)#r   rm   stripr   validate_bucket_nameZvalidate_object_keyr   
ValueError_merge_configrI   r   lowerProtocolHTTPprotocolZHTTPSr   parse_host_portendpointdefault_portr   ZHOST	_get_pathr   r8   rH   setsecurity_tokenSTS_SECURITY_TOKENr   signcredentialsZAUTHORIZATIONnameZget_canonical_querystring)r#   r:   r   	timestampZexpiration_in_secondsr@   r=   Zheaders_to_signr   r4   Z
httpmethodpendpoint_protocolZendpoint_hostendpoint_portZ	full_hostpathr$   r$   r%   generate_pre_signed_url  sZ   












z!BosClient.generate_pre_signed_url)r:   rulesc                 C   $   | j tj|dditd|i|dS )z
        Put Bucket Lifecycle
       
        :type bucket: string
        :param bucket: None

        :type rules: list
        :param rules: None

        :return:**Http Response**
        	   lifecycler;   ruler=   rA   r4   r7   r   rF   rD   rE   )r#   r:   r   r4   r$   r$   r%   put_bucket_lifecycle  s   zBosClient.put_bucket_lifecyclec                 C   rR   )z
        Get Bucket Lifecycle

        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r   r;   r<   r6   rT   r$   r$   r%   get_bucket_lifecycle#  
   
zBosClient.get_bucket_lifecyclec                 C   rR   )z
        Delete Bucket Lifecycle
        
        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r   r;   r<   rp   rT   r$   r$   r%   delete_bucket_lifecycle2  r   z!BosClient.delete_bucket_lifecycle)r:   cors_configurationc                 C   r   )z
        Put Bucket Cors
        :type bucket: string
        :param bucket: None

        :type cors_configuration: list
        :param cors_configuration: None

        :return:**Http Response**
           corsr;   ZcorsConfigurationr   r   )r#   r:   r   r4   r$   r$   r%   put_bucket_corsA     zBosClient.put_bucket_corsc                 C   rR   )z~
        Get Bucket Cors

        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r   r;   r<   r6   rT   r$   r$   r%   get_bucket_corsV  r   zBosClient.get_bucket_corsc                 C   rR   )z
        Delete Bucket Cors

        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r   r;   r<   rp   rT   r$   r$   r%   delete_bucket_corse  r   zBosClient.delete_bucket_cors  c                 C   sX   i }|dur
||d< |dur||d< |dur||d< |dur"||d< | j tj|||dS )  
        Get Object Information of bucket

        :type bucket: string
        :param bucket: None

        :type delimiter: string
        :param delimiter: None

        :type marker: string
        :param marker: None

        :type max_keys: int
        :param max_keys: value <= 1000

        :type prefix: string
        :param prefix: None

        :return:
            **_ListObjectsResponse Class**
        N   maxKeys   prefix   marker	   delimiterr<   r6   )r#   r:   max_keysprefixmarker	delimiterr4   r=   r$   r$   r%   list_objectst  s   zBosClient.list_objectsc                 c   sB    d}	 | j |||||d}|jD ]}|V  q|jr|j}ndS q)

        :param bucket_name:
        :param prefix:
        :param delimiter:
        :param config:
        :return:
        NT)r   r   r   r4   )r   contentsis_truncatedZnext_marker)r#   r:   r   r   r4   r   r>   itemr$   r$   r%   list_all_objects  s   


zBosClient.list_all_objectsc                 C   sH   | d u rd S t | ttfstdt| dkrtdtjdt|  iS )Nz!range should be a list or a tuple   zrange should have length of 2   bytes=%d-%d)rI   listtuple	TypeErrorlenr   r   RANGE)ranger$   r$   r%   _get_range_header_dict  s   z BosClient._get_range_header_dictc                 C   s   i }|   }tjrg }|D ]\}}| }|||f q|}ttj}|D ]\}}||rB|t	|d }t
||t
|< q'||j_| |_dS )a  Sets response.body to http_response and response.user_metadata to a dict consists of all http
        headers starts with 'x-bce-meta-'.

        :param http_response: the http_response object returned by HTTPConnection.getresponse()
        :type http_response: httplib.HTTPResponse

        :param response: general response object which will be returned to the caller
        :type response: baidubce.BceResponse

        :return: always true
        :rtype bool
        NT)
getheadersr   ZPY3r   appendrm   r   BCE_USER_METADATA_PREFIXrY   r   Zconvert_to_unicodemetadatauser_metadatadata)http_responser>   r   Zheaders_listZ
temp_headsr[   r\   r   r$   r$   r%   _parse_bos_object  s(   
zBosClient._parse_bos_objectc           
   	   C   s   i }|durt |}d|i}t |}t|dks|dr#tdt|}	|dur7|	du r2i }	||	tj< |durI|	du rAi }	| 	t
j|	|}	| jt
j|||	||tjdS )z

        :param bucket_name:
        :param key:
        :param range:
        :param traffic_limit:
        :param version_id:
        :param cond_read_write:
        :param config:
        :return:
        N	   versionIdr      /(Key can not be empty or start with '/' .r@   r=   r4   body_parser)r   r   r   rY   r   r1   r   r   BOS_TRAFFIC_LIMIT_get_cond_read_write_headersr   r8   r7   r   )
r#   r:   r   r   traffic_limit
version_idcond_read_writer4   query_paramsrange_headerr$   r$   r%   
get_object  s2   



zBosClient.get_objectStandardc              	   C   s   t |}i }|dur||tj< |dur=t|tr|nt|tr%|dnt|}|dvr4td	|t ||tj
< ntd| jtj|||ddi|tjdS )	zb

        :param bucket_name:
        :param key:
        :param config:
        :return:
        Nzutf-8)r   Z	ExpeditedZLowCostz}invalid tier:{} for restore_object.The valid value is "Standard" or                                  "Expedited" or "LowCost"z(tier can not be None for restore_object.s   restorer;   r   )r   r   r   ZBOS_RESTORE_DAYSrI   r   r   decoder   formatZBOS_RESTORE_TIERr   r7   r   POSTr1   r   )r#   r:   r   daysZtierr4   r@   Ztier_strr$   r$   r%   restore_object  s*   
	
*zBosClient.restore_object @  c                 C   s^   t |d}z$|rt|jj}t| ||}n| }t||| |   W |  dS |  w )NwbT)	openintr   content_lengthr   make_progress_adaptershutilcopyfileobjclose)r   r>   	file_namebuf_sizeprogress_callbackf	file_sizestreamr$   r$   r%   _save_body_to_file%  s   


zBosClient._save_body_to_filec                 C   s   | | | dS )NT)init_from_http_response)r   r>   select_responser$   r$   r%   _parse_select_message6  s   zBosClient._parse_select_messagec           	      C   s8   t |}| j||||||d}|j }|j  |S )zx

        :param bucket_name:
        :param key:
        :param range:
        :param config:
        :return:
        )r   r   r   r4   )r   r   r   r   readr  )	r#   r:   r   r   r   r   r4   r>   sr$   r$   r%   get_object_as_string;  s   



zBosClient.get_object_as_string)r:   r   r  c
                    s   i }
|	durt |	}	d|	i}
t |}t|dks|dr#tdt t|}|dur<|du r7i }||tj< |durN|du rFi }	t
j||}jt
j||||
  fdddS )	a  
        Get Content of Object and Put Content to File

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type file_name: string
        :param file_name: None

        :type range: tuple
        :param range: (0,9) represent get object contents of 0-9 in bytes. 10 bytes date in total.
        :return:
            **HTTP Response**
        Nr   r   r   r   c                    s   t j| | ddS )Nrecv_buf_size)r  )r1   r  _get_config_parameterr   r>   r4   r  r  r#   r$   r%   <lambda>z  s    
z.BosClient.get_object_to_file.<locals>.<lambda>r   )r   r   r   rY   r   r1   r   r   r   r   r   r8   r7   )r#   r:   r   r  r   r4   r  r   r   r   r   r   r$   r  r%   get_object_to_fileL  s4   




zBosClient.get_object_to_filec                 C   s\   i }|durt |}d|i}i }|dur| tj||}t |}| jtj|||||dS )z
        Get head of object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None
        :return:
            **_GetObjectMetaDataResponse Class**
        Nr   rf   )r   r   r   r   rH   r7   )r#   r:   r   r   r   r4   r   r@   r$   r$   r%   get_object_meta_data  s   

zBosClient.get_object_meta_data)r:   r   r   r  c                 C   s  t |}|du rf|	du rf|
du rf|du rf|du rfd}t|D ]F}ztj||| |dd}
W  n5 tye } z)||d k rPtd|d |t	| W Y d}~qt
d|t	| d}
W Y d}~qd}~ww |rmt |}|	rtt |	}	|
r{t |
}
|rt |}|durt |}|rt |}| j||||	|
||||||||d}|tjkrtd	tj d
di}|dur||d< |rt||}| jtj||||||dS )a4  
        Put an appendable object to BOS or add content to an appendable object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type content_length: long
        :type offset: long
        :return:
            **HTTP Response**
        N   r  lengthr     6CRC32 calculation failed, retrying (attempt %d/%d): %s.CRC32 calculation failed after %d attempts: %s)r  content_md5content_typecontent_sha256content_crc32content_crc32ccontent_crc32c_flagcontent_crc64ecmar   r   user_headersr   object_taggingDObject length should be less than %d. Use multi-part upload instead.s   appendr;   s   offsetrb   )r   r   r   r   get_crc32_from_fpr  	Exception_loggerwarningr   error_prepare_object_headersr   ZMAX_APPEND_OBJECT_LENGTHr   r  r7   r   r   )r#   r:   r   r   r  r&  offsetr'  r   r(  r)  r*  r+  r,  r   r-  r  r   r.  r4   max_retriesretry_countrP   r@   r=   r$   r$   r%   append_object  s   
#







zBosClient.append_object)r:   r   r   c                 C   s   t |}t|tr|tj}d}z\t|}|	du r't	j
|| |dd}	| jdi d|d|d|d|dt|d	|d
|d|d|d|	d|
d|d|d|d|d|d|d|W |durn|  S S |durx|  w w )z
        Create an appendable object and put content of string to the object
        or add content of string to an appendable object
        Nr  r  r:   r   r   r&  r  r6  r'  r   r(  r)  r*  r+  r,  r   r-  r  r   r4   r$   )r   r   rI   r   encodebaidubceDEFAULT_ENCODINGioBytesIOr   r0  r  r9  r   r  )r#   r:   r   r   r&  r6  r'  r   r(  r)  r*  r+  r,  r   r-  r  r   r4   fpr$   r$   r%   append_object_from_string   sd   


	



z#BosClient.append_object_from_stringc                 C   s  t |}|du rf|du rf|du rf|	du rf|du rfd}t|D ]F}ztj||| |dd}W  n5 tye } z)||d k rPtd|d |t	| W Y d}~qt
d|t	| d}W Y d}~qd}~ww |rmt |}|rtt |}|r{t |}|	rt |	}	|
durt |
}
|rt |}| jdi d|d	|d
|d|d|d|	d|
d|d|d|d|d|d|d|d|d|}|dur| tj||}|tjkrtdtj |rt||}| jtj|||||dS )al  
        Put object and put content of file to the object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type fp: FILE
        :param fp: None

        :type file_size: long
        :type offset: long
        :type content_length: long
        :return:
            **HTTP Response**
        Nr   r  r!  r#  r$  r%  r  r&  r'  r(  r)  r*  r+  r,  r   r   r-  
encryptioncustomer_keycustomer_key_md5r   r.  r/  )rA   r@   r4   r$   )r   r   r   r   r0  r  r1  r2  r3  r   r4  r5  r   r   rF   r   MAX_PUT_OBJECT_LENGTHr   r  r7   )r#   r:   r   r   r  r&  r'  r(  r)  r*  r+  r,  r   r   r-  rB  rC  rD  r  r   r.  r   r4   r7  r8  rP   r@   r$   r$   r%   
put_object7  s   
*







	

zBosClient.put_object)bucketr   r   c                 C   s   t |}t|tr|tj}d}zbt|}|du r't	j
|| |dd}| j|||fi dt|d|d|d|d|d	|d
|	d|
d|d|d|d|d|d|d|d|d|d|d|W |durt|  S S |dur~|  w w )af  
        Create object and put content of string to the object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type input_content: string
        :param input_content: None

        :type options: dict
        :param options: None
        :return:
            **HTTP Response**
        Nr  r:  r  r&  r'  r(  r)  r*  r+  r,  r   r   r-  rB  rC  rD  r  r   r.  r   r4   )r   r   rI   r   r;  r<  r=  r>  r?  r   r0  r  rF  r   r  )r#   rG  r   r   r&  r'  r(  r)  r*  r+  r,  r   r   r-  rB  rC  rD  r  r   r.  r   r4   r@  r$   r$   r%   put_object_from_string  sl   
%

	



z BosClient.put_object_from_string)rG  r   r  c                 C   s  t |}t|d}zv|du r|dtj | }|d |du r1| |d}tj	|||d}|du r:t
|}| j|||fi d|d|d|d	|d
|d|	d|
d|d|d|d|d|d|d|d|d|d|d|d|W |  S |  w )a^  
        Put object and put content of file to the object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type file_name: string
        :param file_name: None

        :type options: dict
        :param options: None
        :return:
            **HttpResponse Class**
        rbNr   r  r!  r  r&  r'  r(  r)  r*  r+  r,  r   r   r-  rB  rC  rD  r  r   r.  r   r4   )r   r   r  seekosSEEK_ENDtellr  r   r0  guess_content_type_by_file_namerF  r  )r#   rG  r   r  r  r&  r'  r(  r)  r*  r+  r,  r   r   r-  rB  rC  rD  r  r   r.  r   r4   r@  r  r$   r$   r%   put_object_from_file  sl   
(


	
zBosClient.put_object_from_file)source_bucket_name
source_keytarget_bucket_name
target_keyc              
   C   s   t |}t |}| j||||	||d}tdt ||f d}|dur/|dt |  }||tj< |dur=||tj< |dusE|durKd|tj< nd|tj< |
durlz	t	
||
d}W n tyk } z|d}~ww | jtj||||tjd	S )
a{  
        Copy one object to another object

        :type source_bucket: string
        :param source_bucket: None

        :type source_key: string
        :param source_key: None

        :type target_bucket: string
        :param target_bucket: None

        :type target_key: string
        :param target_key: None
        :return:
            **HttpResponse Class**
        )r'  r   r   r-  r   r.     /%s/%sFNs   ?versionId=%ss   replaces   copyT)r@   r4   r   )r   r   r5  r   normalize_stringr   BCE_COPY_SOURCEBCE_COPY_SOURCE_IF_MATCHZBCE_COPY_METADATA_DIRECTIVEr1   _get_user_headerr1  r7   r   rF   r   Zparse_copy_object_response)r#   rP  rQ  rR  rS  etagr'  r   r   r-  Zcopy_object_user_headersr   r.  Zsource_version_idr4   r@   Zmerge_source_keyrP   r$   r$   r%   copy_object6  sP   
"



zBosClient.copy_objectc                 C   s>   i }|durt |}d|i}t |}| jtj||||dS )z
        Delete Object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None
        :return:
            **HttpResponse Class**
        Nr   r<   r   )r#   r:   r   r   r4   r   r$   r$   r%   delete_object~  s   

zBosClient.delete_object)r:   key_listc                 C   s2   dd |D }| j tj|td|iddi|dS )z
        Delete Multiple Objects

        :type bucket: string
        :param bucket: None

        :type key_list: string list
        :param key_list: None
        :return:
            **HttpResponse Class**
        c                 S   s   g | ]	}d t |iqS r   )r   rm   ).0r[   r$   r$   r%   
<listcomp>  s    z5BosClient.delete_multiple_objects.<locals>.<listcomp>objectss   deleter;   rA   r=   r4   r7   r   r   rD   rE   )r#   r:   r\  r4   Zkey_list_jsonr$   r$   r%   delete_multiple_objects  s   z!BosClient.delete_multiple_objects)source_buckettarget_buckettarget_prefixc                 C   sD   dt |i}|durt ||d< | jtj|ddit||dS )z
        Put Bucket Logging

        :type source_bucket: string
        :param source_bucket: None

        :type target_bucket: string
        :param target_bucket: None
        :return:
            **HttpResponse Class**
        ZtargetBucketNZtargetPrefix   loggingr;   r   )r   rm   r7   r   rF   rD   rE   )r#   rd  re  rf  r4   rA   r$   r$   r%   put_bucket_logging  s   zBosClient.put_bucket_loggingc                 C   rR   )z
        Get Bucket Logging

        :type bucket_name: string
        :param bucket_name: None
        :return:
            **HttpResponse Class**
        rg  r;   r<   r6   rT   r$   r$   r%   get_bucket_logging  r   zBosClient.get_bucket_loggingc                 C   rR   )z
        Delete Bucket Logging

        :type bucket_name: string
        :param bucket_name: None
        :return:
            **HttpResponse Class**
        rg  r;   r<   rp   rT   r$   r$   r%   delete_bucket_logging  r   zBosClient.delete_bucket_loggingc           	   
   C   s   t |}i }|dur||tj< |durt||tj< ntj|tj< |dur?z	t	
||d}W n ty> } z|d}~ww | jtj|||ddi|dS )z
        Initialize multi_upload_file.

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None
        :return:
            **HttpResponse**
        NF   uploadsr;   rf   )r   r   r   BOS_STORAGE_CLASSr   convert_to_standard_stringrC   r   OCTET_STREAMr1   rX  r1  r7   r   r   )	r#   r:   r   r'  r   r-  r4   r@   rP   r$   r$   r%   initiate_multipart_upload  s,   

z#BosClient.initiate_multipart_upload)r:   r   	upload_idpart_number	part_sizepart_fpc                 C   s  t |}|tjk s|tjkrtd|tjtjf |tjkr&tdtj |du r|du r|	du r|
du r|du rd}t|D ]F}ztj	||| 
|dd}W  n5 ty } z)||d k rqtd|d |t| W Y d}~q@td	|t| d}W Y d}~q@d}~ww |rt |}|	rt |	}	|rt |}|
rt |
}
|rt |}|rt |}| j|||	||
|||d
}|rt|||}| jtj||||||d|dS )a?  
        Upload a part.

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type upload_id: string
        :param upload_id: None

        :type part_number: int
        :param part_number: None

        :type part_size: int or long
        :param part_size: None

        :type part_fp: file pointer
        :param part_fp: not None

        :type part_md5: str
        :param part_md5: None

        :type config: dict
        :param config: None

        :return:
               **HttpResponse**
        z9Invalid part_number %d. The valid range is from %d to %d.z+Single part length should be less than %d. Nr   r  r!  r#  r$  r%  )r  r&  r(  r)  r*  r+  r,  r   s
   partNumber   uploadIdrb   )r   r   r   ZMIN_PART_NUMBERZMAX_PART_NUMBERr   rE  r   r   r0  r  r1  r2  r3  r   r4  r5  r  r7   r   rF   )r#   r:   r   rp  rq  rr  rs  part_md5
part_crc32part_sha256part_crc32cpart_crc32c_flagpart_crc64ecmar  r   r4   r7  r8  rP   r@   r$   r$   r%   upload_part  sz   
'








zBosClient.upload_part)rP  rQ  rR  rS  rp  rq  rr  r6  c                 C   s   t |}t |}| j|
||d}tdt ||f d|tj< d||| d f }||tj< |	dur:|	|tj< | j	t
j|||||d|dS )	a  
        Copy part.

        :type source_bucket_name: string
        :param source_bucket_name: None

        :type source_key: string
        :param source_key: None

        :type target_bucket_name: string
        :param target_bucket_name: None

        :type target_key: string
        :param target_key: None

        :type upload_id: string
        :param upload_id: None

        :return:
            **HttpResponse**
        )r'  r   r   rT  Fr   r#  Nrt  rf   )r   r   r5  r   rU  r   rV  ZBCE_COPY_SOURCE_RANGErW  r7   r   rF   )r#   rP  rQ  rR  rS  rp  rq  rr  r6  rY  r'  r   r   r4   r@   r   r$   r$   r%   upload_part_copyq  s2   
&




zBosClient.upload_part_copy)r:   r   rp  rq  rr  r  r6  c                 C   s\   t |}t|d}z|| | j||||||||	|
||||||dW |  S |  w )z

        :param bucket_name:
        :param key:
        :param upload_id:
        :param part_number:
        :param part_size:
        :param file_name:
        :param offset:
        :param part_md5:
        :param config:
        :return:
        rI  )	rv  rw  rx  ry  rz  r{  r  r   r4   )r   r   r  rJ  r|  r  )r#   r:   r   rp  rq  rr  r  r6  rv  rw  rx  ry  rz  r{  r  r   r4   r  r$   r$   r%   upload_part_from_file  s   


zBosClient.upload_part_from_file)r:   r   rp  	part_listc              	   C   sd   t |}| jtj|||||	|
d}|dur| tj||}| jtj||t	
d|i|d|i|dS )ac  
        After finish all the task, complete multi_upload_file.

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type upload_id: string
        :param upload_id: None

        :type part_list: list
        :param part_list: None

        :return:
            **HttpResponse**
        )r'  r   r-  r)  r*  r+  r,  Npartsru  rb   )r   r   r5  r   rB   r   r   r   r7   rD   rE   )r#   r:   r   rp  r  r-  r   r)  r*  r+  r,  r   r4   r@   r$   r$   r%   complete_multipart_upload  s*   
 	z#BosClient.complete_multipart_upload)r:   r   rp  c                 C   s$   t |}| jtj||d|i|dS )a  
        Abort upload a part which is being uploading.

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type upload_id: string
        :param upload_id: None
        :return:
            **HttpResponse**
        ru  r<   r   )r#   r:   r   rp  r4   r$   r$   r%   abort_multipart_upload	  s
   
z BosClient.abort_multipart_uploadc                 C   sH   t |}d|i}|dur||d< |dur||d< | jtj||||dS )a  
        List all the parts that have been upload success.

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :type upload_id: string
        :param upload_id: None

        :type max_parts: int
        :param max_parts: None

        :type part_number_marker: string
        :param part_number_marker: None
        :return:
            **_ListPartsResponse Class**
        ru  Ns   maxPartss   partNumberMarkerr<   r   )r#   r:   r   rp  Z	max_partspart_number_markerr4   r=   r$   r$   r%   
list_parts  s   
zBosClient.list_partsc                 c   sJ    t |}d}	 | j|||||d}|jD ]}|V  q|js!dS |j}q	)z|

        :param bucket_name:
        :param key:
        :param upload_id:
        :param config:
        :return:
        NT)r  r4   )r   r   r  r  r   Znext_part_number_marker)r#   r:   r   rp  r4   r  r>   r   r$   r$   r%   list_all_parts?  s   



zBosClient.list_all_partsc                 C   s\   ddi}|dur||d< |dur||d< |dur||d< |dur$||d< | j tj|||dS )	a|  
        List all Multipart upload task which haven't been ended.(Completed Init_MultiPartUpload
        but not completed Complete_MultiPartUpload or Abort_MultiPartUpload)

        :type bucket: string
        :param bucket: None

        :type delimiter: string
        :param delimiter: None

        :type max_uploads: int
        :param max_uploads: <=1000

        :type key_marker: string
        :param key_marker: None

        :type prefix: string
        :param prefix: None

        :type upload_id_marker: string
        :param upload_id_marker:
        :return:
            **_ListMultipartUploadResponse Class**
        rk  r;   Nr   s
   maxUploadss	   keyMarkerr   r<   r6   )r#   r:   Zmax_uploads
key_markerr   r   r4   r=   r$   r$   r%   list_multipart_uploadsT  s   z BosClient.list_multipart_uploadsc                 c   sl    d}	 | j |||||d}|jD ]}|V  q|jsdS |jdur%|j}nt|jdkr3|jd j}ndS q)r   NT)r  r   r   r4   r   )r  Zuploadsr   Znext_key_markerr   r   )r#   r:   r   r   r4   r  r>   r   r$   r$   r%   list_all_multipart_uploads|  s&   


z$BosClient.list_all_multipart_uploadsc                 C   s   |	  rtd| d S z'| j||||||||
|||||d}|||jjd td| W d S  tyK } z
td| |d }~ww )Nz(upload task canceled with partNumber={}!)rw  ry  rz  r{  r  r   )
partNumberZeTagz'upload task success with partNumber={}!z&upload task failed with partNumber={}!)	r,   r2  debugr   r~  r   r   rY  r1  )r#   r:   Z
object_keyrp  rq  rr  r  r6  r  uploadTaskHandlerw  ry  rz  r{  r  r   r>   rP   r$   r$   r%   _upload_task  s&   

zBosClient._upload_task   c           $      C   sH  |dks|dkrt dtj|}|dkrt d|du s"|dkr&t }|d d }|| }|| dkr:|d7 }|du rAt }| j|||||	d	j}t	|}g }d}d}g }g }t
|d
L}|dkr|}||k rl|}t|||}|||f || j||||||||||ddd||}|| ||8 }||7 }|d7 }|dksdW d   n1 sw   Y  t|td | rtd | j|||d dS t||krtd | j|||d dS |jdd d |r|d d } tdt|D ]}!||! \}"}#t| |"|#} q| dM } |
du r| }
| j|||||
||||d	 dS )zn
        Multipart Upload file to bos

        param chunk_size: part size , default part size is 5MB
        i   r   zEchunk size is valid, it should be more than 0 and not nore than 5120!l       PC z'File size must not be more than 48.8TB!Nr#  i   )r'  r   r-  rI  )Zreturn_whenz!putting super object is canceled!)rp  Fzputting super object failed!c                 S   s   | d S )Nr  r$   )xr$   r$   r%   r    s    z6BosClient.put_super_object_from_file.<locals>.<lambda>r]  l    )r)  r*  r+  r,  r   T)r   rK  r   getsizemultiprocessing	cpu_countr   ro  rp  r   r  r   r0  r   Zsubmitr  r   r	   r,   r2  r  r  r   sortr   Zcrc32_combiner  )$r#   r:   r   r  
chunk_sizeZ
thread_numr  r'  r   r-  r)  r*  r+  r,  r  r   r   r4   Z	left_sizerr  Z
total_partrp  executorZ	all_tasksr6  rq  r  Zpart_crc_listr@  Zcurrent_part_sizeZpart_crcZ	temp_taskZfinal_crc32icrcr"  r$   r$   r%   put_super_object_from_file  s   




z$BosClient.put_super_object_from_file)r:   r   rZ   c              	   C   s@   t |}| jtj||tjd|itjdt	j
tjiddi|dS )z
        Set Access Control Level of object

        :type bucket: string
        :param bucket: None

        :type acl: list of grant
        :param acl: None
        :return:
            **HttpResponse Class**
        r_   r`   rS   r;   rb   r   )r#   r:   r   rZ   r4   r$   r$   r%   set_object_acl		  s   


zBosClient.set_object_aclc           	      C   s   t |}d}d}|durtjt |i}|d7 }|dur)tjt |i}|d7 }|dur9tjt |i}|d7 }|dkrAtd|dkrItd| jtj	|||ddi|d	S )
a  

        :type bucket_name: string
        :param bucket_name: None

        :type key: string
        :param key: None

        :type canned_acl: string
        :param canned_acl: for header 'x-bce-acl', it's value only is
        canned_acl.PRIVATE or canned_acl.PRIVATE_READ

        :type grant_read: string
        :param grant_read: Object id of getting READ right permission.
        for exapmle,grant_read = 'id="6c47...4c94",id="8c42...4c94"'

        :type grant_full_control: string
        :param grant_full_control: Object id of getting READ right permission.
        for exapmle,grant_full_control = 'id="6c47...4c94",id="8c42...4c94"'

        :param config:
        :return:
            **HttpResponse Class**
        Nr   r#  z,donn't give any object canned acl arguments!r   z5cann't get more than one object canned acl arguments!rS   r;   rf   )
r   r   r   rg   ZBOS_GRANT_READZBOS_GRANT_FULL_CONTROLr   r7   r   rF   )	r#   r:   r   re   Z
grant_readZgrant_full_controlr4   r@   num_argsr$   r$   r%   set_object_canned_acl 	  s.   
zBosClient.set_object_canned_aclc                 C   $   t |}| jtj||ddi|dS )z
        Get Access Control Level of object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :return:
            **HttpResponse Class**
        rS   r;   r<   r   r#   r:   r   r4   r$   r$   r%   get_object_aclW	     
zBosClient.get_object_aclc                 C   r  )z
        Get Access Control Level of  object

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: None

        :return:
            **HttpResponse Class**
        rS   r;   r<   r   r  r$   r$   r%   delete_object_aclm	  r  zBosClient.delete_object_acl)r:   r   urlc                 C   s^   t |}i }t ||tj< |dur||tj< |dur!||tj< | jtj|||ddi|dS )a  
        fetch object with given url and save to Baidu object storage

        :type bucket: string
        :param bucket: None

        :type key: string
        :param key: object name to be saved

        :type url:string
        :param url: url of resource to be fetched

        :type fetch_mode:string
        :param fetch_mode: fetch mode for get resource, valid value only is
        'sync' and 'async'

        :return:
            **HttpResponse Class**
        Ns   fetchr;   rf   )	r   r   r   ZBOS_FETCH_SOURCEZBOS_FETCH_MODErl  r7   r   r   )r#   r:   r   r  Z
fetch_moder   r4   r@   r$   r$   r%   fetch_object	  s   


zBosClient.fetch_object)r:   rS  symlinkforbid_overwritec
                 C   s   t |}t |}|du rt|}| j|||d}
||
tj< |dur1|r,d|
tj< nd|
tj< |dur=t ||
tj< | j	t
j|||
ddi|	dS )a  
        put object symlink

        :type bucket: string
        :param bucket: None

        :type key: string
        :type key: object name

        :type symlink: string
        :type symlink_key: symlink name

        :return:
            **HttpResponse Class**
        N)r   r'  r   s   trues   false   symlinkr;   rf   )r   r   r   rN  r5  r   ZBOS_SYMLINK_TARGETZBOS_FORBID_OVERWRITEZBOS_SYMLINK_BUCKETr7   r   rF   )r#   r:   rS  r  r  r   r   re  r'  r4   r@   r$   r$   r%   put_object_symlink	  s,   




zBosClient.put_object_symlink)r:   r  c                 C   s$   t |}| jtj||ddi|dS )z
        Get symlink info

        :type bucket: string
        :param bucket: None

        :type symlink: string
        :param symlink: symlink

        :return:
            **HttpResponse Class**
        r  r;   r<   r   )r#   r:   r  r4   r   r$   r$   r%   get_object_symlink	  r  zBosClient.get_object_symlink)r:   r   select_object_argsc                    s   t |}|pi }d|v rd|d v rd}nd|v r#d|d v r#d}nd}t  | jtj||tjd|itj	d|d	|d
| fddd  S )a-  

        :type bucket_name: string
        :param bucket_name: bucket name

        :type key: string
        :param key: object name

        :type select_object_args: dict
        :param select_object_args: requesta parameters for select object api

        :param config:
        :return:
        ZinputSerializationrD   s   jsoncsvs   csvs   parquetZselectRequestr`   r;   )s   selects   typec                    s   t | | S r2   )r1   r  r  r  r$   r%   r  

  s    z)BosClient.select_object.<locals>.<lambda>)rA   r@   r=   r4   r   )
r   r   SelectResponser7   r   r   rD   rE   r1   r]   )r#   r:   r   r  r@   r4   Zselect_typer$   r  r%   select_object	  s&   

zBosClient.select_objectc                 C      | j tjddi|dS )zI
        get user quota

        :param config:
        :return:
        	   userQuotar;   r<   r6   r3   r$   r$   r%   get_user_quota
     zBosClient.get_user_quota)max_bucket_countmax_capacity_mega_bytesc                 C   s$   | j tjt||dddi|dS )a  
        put user quota

        :type max_bucket_count: int
        :param max_bucket_count: max bucket count

        :type max_capacity_mega_bytes: long
        :param max_capacity_mega_bytes: max capacity mega bytes

        :param config:
        :return:
        )ZmaxBucketCountZmaxCapacityMegaBytesr  r;   ra  r   )r#   r  r  r4   r$   r$   r%   put_user_quota
  s   zBosClient.put_user_quotac                 C   r  )zL
        delete user quota

        :param config:
        :return:
        r  r;   r<   rp   r3   r$   r$   r%   delete_user_quota-
  r  zBosClient.delete_user_quotac                 C   rR   )z
        get notification

        :type bucket_name: string
        :param bucket_name: bucket name

        :param config:
        :return:
           notificationr;   r:   r=   r4   r6   rT   r$   r$   r%   get_notification8
  s   zBosClient.get_notification)r:   notificationsc                 C   s$   | j tj|td|iddi|dS )z
        put user quota

        :type bucket_name: string
        :param bucket_name: bucket

        :type notifications: list of dict
        :param notifications: notifacation param

        :param config:
        :return:
        r  r  r;   r:   rA   r=   r4   r   )r#   r:   r  r4   r$   r$   r%   put_notificationH
  s
   zBosClient.put_notificationc                 C   rR   )z
        delete notification

        :type bucket_name: string
        :param bucket_name: bucket name

        :param config:
        :return:
        r  r;   r  rp   rT   r$   r$   r%   delete_notification[
  s   zBosClient.delete_notification)r:   mirror_argsc                 C   s*   | j tj|tjd|itjdddi|dS )z
        put bucket mirroring

        :type bucket_name: string
        :param bucket_name: bucket name

        :param mirror_args: mirror conf
        :return:
        ZbucketMirroringConfigurationr`   	   mirroringr;   r  r7   r   rF   rD   rE   r1   r]   )r#   r:   r  r4   r$   r$   r%   put_bucket_mirroringj
  s   zBosClient.put_bucket_mirroringc                 C   rR   )z
        get bucket mirroring

        :type bucket_name: string
        :param bucket_name: bucket name

        :return:
        r  r;   r  r6   rT   r$   r$   r%   get_bucket_mirroring}
  rV   zBosClient.get_bucket_mirroringc                 C   rR   )z
        delete bucket mirroring

        :type bucket_name: string
        :param bucket_name: bucket name

        :return:
        r  r;   r  rp   rT   r$   r$   r%   delete_bucket_mirroring
  rV   z!BosClient.delete_bucket_mirroring)r:   r   obj_tag_argsc                 C   s(   | j tj||tj|tjdddi|dS )  
        put object tagging

        :type bucket_name: string
        :param bucket_name: bucket name

        :type key: string
        :param key: object name

        :type obj_tag_args: dict
        :param obj_tag_args: object tagging args

        :return:
        r`      taggingr;   )r:   r   rA   r=   r4   r  )r#   r:   r   r  r4   r$   r$   r%   put_object_tagging
  s   zBosClient.put_object_taggingc                 C   s0   i }t ||tj< | jtj|||ddi|dS )r  r  r;   )r:   r   r@   r=   r4   )r   r   r   BOS_TAGGINGr7   r   rF   )r#   r:   r   Z
tag_headerr4   r@   r$   r$   r%   put_object_tagging_canned
  s   z#BosClient.put_object_tagging_cannedc                 C   r  )z
        delete object tagging

        :type bucket_name: string
        :param bucket_name: bucket name

        :type key: string
        :param key: object name

        :return:
        r  r;   r:   r   r=   r4   r   r  r$   r$   r%   delete_object_tagging
  s   
zBosClient.delete_object_taggingc                 C   s   | j tj||ddi|dS )z
        put object tagging

        :type bucket_name: string
        :param bucket_name: bucket name

        :type key: string
        :param key: object name

        :return:
        r  r;   r  r6   r  r$   r$   r%   get_object_tagging
  s   zBosClient.get_object_tagging)r:   statusc                 C   s4   | j tj|tjd|itjddditjt	j
i|dS )z
        put bucket versioning

        :type bucket_name: string
        :param bucket_name: bucket name

        :type status: string
        :param key: version status:disable/enabled/suspended

        :return:
        r  r`   
   versioningr;   )r:   rA   r=   r@   r4   rc   )r#   r:   r  r4   r$   r$   r%   put_bucket_versioning
  s   
zBosClient.put_bucket_versioningc                 C   rR   )z
        get bucket versioning

        :type bucket_name: string
        :param bucket_name: bucket name

        :return:
        r  r;   r  r6   rT   r$   r$   r%   get_bucket_versioning  rV   zBosClient.get_bucket_versioningc           	      C   sl   ddi}|dur||d< |dur||d< |dur||d< |dur$||d< |dur,||d< | j tj|||d	S )
r   s   versionsr;   Nr   r   r   r   s   versionIdMarkerr<   r6   )	r#   r:   r   r   r   Zversion_markerr   r4   r=   r$   r$   r%   list_objects_versions  s   zBosClient.list_objects_versions)r:   retention_daysc                 C   r   )z
        init bucket object lock
        :type bucket: string
        :param bucket: None

        :type retention_days: int
        :param retention_days: None

        :return:**Http Response**
        
   objectlockr;   ZretentionDaysr   rb  )r#   r:   r  r4   r$   r$   r%   init_bucket_object_lockD  r   z!BosClient.init_bucket_object_lockc                 C   rR   )z
        get bucket object lock

        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r  r;   r<   r6   rT   r$   r$   r%   get_bucket_object_lockY  r   z BosClient.get_bucket_object_lockc                 C   rR   )z
        Delete Bucket Object Lock

        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r  r;   r<   rp   rT   r$   r$   r%   delete_bucket_object_lockh  r   z#BosClient.delete_bucket_object_lockc                 C   rR   )z
        complete bucket object lock
        :type bucket: string
        :param bucket: None

        :type retention_days: int
        :param retention_days: None

        :return:**Http Response**
        s   completeobjectlockr;   r<   )r7   r   r   rT   r$   r$   r%   complete_bucket_object_lockw  s
   z%BosClient.complete_bucket_object_lock)r:   extend_retent_daysc                 C   r   )z
        extend bucket object lock
        :type bucket: string
        :param bucket: None

        :type extend_retent_days: int
        :param extend_retent_days: None

        :return:**Http Response**
        s   extendobjectlockr;   ZextendRetentionDaysr   rb  )r#   r:   r  r4   r$   r$   r%   extend_bucket_object_lock  r   z#BosClient.extend_bucket_object_lockc                 C   rR   z~
        get bucket quota
        :type bucket: string
        :param bucket: None

        :return:**Http Response**
           quotar;   r<   r6   rT   r$   r$   r%   get_bucket_quota  rx   zBosClient.get_bucket_quota)r:   
quota_confc                 C   &   | j tj|tj|tjdddi|dS )z
        put quota conf of bucket
        :type bucket: string
        :param bucket: None

        :type retention_days: int
        :param retention_days: None

        :return:**Http Response**
        r`   r  r;   ra  r  )r#   r:   r  r4   r$   r$   r%   put_bucket_quota     zBosClient.put_bucket_quotac                 C   rR   r  rp   rT   r$   r$   r%   delete_bucket_quota  rx   zBosClient.delete_bucket_quotac                 C   rR   )z
        get bucket tagging
        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r  r;   r<   r6   rT   r$   r$   r%   get_bucket_tagging  rx   zBosClient.get_bucket_tagging)r:   tag_confc                 C   r  )z
        put tagging conf of bucket
        :type bucket: string
        :param bucket: None

        :type retention_days: int
        :param retention_days: None

        :return:**Http Response**
        r`   r  r;   ra  r  )r#   r:   r  r4   r$   r$   r%   put_bucket_tagging  r  zBosClient.put_bucket_taggingc                 C   rR   )z
        delete bucket tagging
        :type bucket: string
        :param bucket: None

        :return:**Http Response**
        r  r;   r<   rp   rT   r$   r$   r%   delete_bucket_tagging  rx   zBosClient.delete_bucket_taggingc              
   C   s~  i }| d ur| r| dk rt dt| |tj< |d ur$t||tj< |d ur1t||tj< nt	j
|tj< |d urCt||tj< |d urOt||tj< |d ur[t||tj< |d urgt||tj< |d urst||tj< |d urdt| |tj< |	d urd}t }t|	tstdt|	D ]*\}}||  t|}t|}tj| }|||< |t|7 }|t|7 }q|tjkrt dtj t|t|	krt d|
d ur|
|tj< |d urt||tj< |d urt||tj< |d urt||tj< |d ur&z	t !||d}W n t"y% } z|d }~ww |d ur0||tj#< |d ur=t||tj$< |S )Nr   z&content_length should not be negative.s   "%s"z%user_metadata should be of type dict.z,Metadata size should not be greater than %d.z%user_metadata has duplicate elements.F)%r   r   r   r   ZCONTENT_LENGTHr   rm  ZCONTENT_MD5rC   r   rn  ZBCE_CONTENT_SHA256ZBCE_CONTENT_CRC32ZBCE_CONTENT_CRC32CZBCE_CONTENT_CRC32C_FLAGZBCE_CONTENT_CRC64ECMAZETAGr   rI   dictr   r   addr   r   r   r   ZMAX_USER_METADATA_SIZErl  ZBOS_SERVER_SIDE_ENCRYPTIONZ'BOS_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEYZ+BOS_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5r1   rX  r1  r   r  )r  r&  r'  r(  r)  r*  r+  r,  rY  r   r   r-  rB  rC  rD  r   r.  r@   Z	meta_sizeZmeta_data_setr[   r\   Znormalized_keyrP   r$   r$   r%   r5  	  s~   










z!BosClient._prepare_object_headersc                 C   sx   t j}| tjks| tjkr|tt jt jt j	t j
g}t|D ]\}}t|}||v r2|||< q td|| f |S )a&  
        get if condition headers
        :type http_method: string
        :param http_method: GET, HEAD, PUT, POST

        :type cond_read_write: string
        :param cond_read_write: put_object, complete_multipart_upload, get_object, get_object_meta_data

        :return: headers
        z%s is not valid in %s)r   ZBOS_COND_READ_WRITE_HEADERSr   r8   rH   unionr   ZBOS_IF_MODIFIED_SINCEZBOS_IF_UNMODIFIED_SINCEZBOS_IF_MATCHZBOS_IF_NONE_MATCHr   r   rm  r   )http_methodr@   r   Zcond_read_write_setr[   r\   r$   r$   r%   r   i  s   

z&BosClient._get_cond_read_write_headersc                 C   s   t |ts	tdtj}|s |ttjtjtj	tj
tjg}n|ttjtjtjg}t|D ]\}}t|}|tjkrDt|}||v rL|| |< q1| S )Nz$user_headers should be of type dict.)rI   r  r   r   ZBOS_BASE_ALLOW_HEADERSr  r   ZCACHE_CONTROLZCONTENT_ENCODINGZCONTENT_DISPOSITIONZEXPIRESZBOS_PROCESSZBCE_COPY_SOURCE_IF_NONE_MATCHZ#BCE_COPY_SOURCE_IF_UNMODIFIED_SINCEZ!BCE_COPY_SOURCE_IF_MODIFIED_SINCEr   r   rm  ZBOS_OBJECT_EXPIRES)r@   r-  Zis_copyZbos_headersZuser_headers_setr[   r\   r$   r$   r%   rX    s,   






zBosClient._get_user_headerc                 C   s.   d }|d urt ||}|d ur|S t | j|S r2   )getattrr4   )r#   r4   attrr+   r$   r$   r%   r    s   
zBosClient._get_config_parameterc                 C   s^   | j }|r| j}t|| j\}}}| js t|s t||r'tt	j
|S tt	j
||S r2   )r   backup_endpointr   r   r   cname_enabledis_cname_like_hostZis_custom_hostZ
append_urir   Z
URL_PREFIX)r4   r:   r   Zuse_backup_endpointhostr   Z	host_namer   r$   r$   r%   r     s   zBosClient._get_pathc                 C   s4   t  | j}|d ur|| | ||}||_|S r2   )copyr4   Zmerge_non_none_values_change_user_endpointr   )r#   r4   r:   Z
new_configr   r$   r$   r%   r     s   
zBosClient._merge_configc                 C   s*  t |j|j\}}}t|d}|j}t |o t|dk}t 	|r)|jS |j
r/|jS |js7t |r@|r=td|jS |d ur{|r{|tro|d}	t|	dk rY|jS |	d d t| d |	d  }
t|
S t|d t| S t|dkr|d ur|d t|krtd	|jS )
N   .r   z<endpoint is not cname domain, please set cname_enabled=Falses   //r   r   r#     z@your endpoint's bucket_name is not equal your query bucket_name!)r   r   r   r   r   r   splitZis_bos_suffixed_hostr   Z
check_ipv4Zpath_style_enabler  r  r   rY   HTTP_PROTOCOL_HEAD)r#   r4   r:   r   Zuser_host_namer   Zuser_endpoint_splitZuser_endpointZis_bos_path_style_hostZhttp_head_splitZbucket_endpointr$   r$   r%   r    sD   



zBosClient._change_user_endpointc                 C   s.   t |tsdS |jtjjkrtd dS dS )NFz*BOS retry condition matched: 403 ForbiddenT)rI   r   rK   rL   rM   rN   r2  r  )r4   r4  r$   r$   r%   _need_retry_for_bos  s   

zBosClient._need_retry_for_bosc                 C   sb   t | trdS t | tr/| jtjjkrdS | jtjjkrdS | jtj	kr&dS | jtjj
kr/dS dS )NTF)rI   IOErrorr   rK   rL   rM   INTERNAL_SERVER_ERRORSERVICE_UNAVAILABLEcodeZREQUEST_EXPIREDrN   )r4  r$   r$   r%   _need_retry_backup_endpoint  s   

z%BosClient._need_retry_backup_endpointc	                 C   s   t | | ||}t|||}	|d u rtj}|jd ur(|p!i }|j|tj	< d }
d }d }t
|dr<t
|dr<| }zt|tjtj|g||	|||W S  tyc } z
|}
|}W Y d }~nd }~ww |	}|d ur|jd urt|jrz*|d ur|| td|j t|||d}	t|tjtj|g||	|||d	W S  ty } z
|}
|}W Y d }~nd }~ww |d urt||jrz!|d ur|| td|j t|tjtj|g|||||W S  ty } z
|}
|}W Y d }~nd }~ww |
d u r |
)NrM  rJ  s)   Retry for backup endpoint error code: %s.Ts   Retry for BOS error code: %s.)r   r   r   r1   r   r   Z
parse_jsonr   r   r   hasattrrM  r   send_requestr   r   Zparse_errorr   r  r  rJ   rJ  r2  r  rK   r  )r#   r  r:   r   rA   r@   r=   r4   r   r   Zlast_exceptionrP   Zbody_initial_offsetexZoriginal_pathr$   r$   r%   r7     st   






zBosClient._send_requestr2   )NFN)NNN)NN)r   NNNN)NNNNN)Nr   N)r  N)NNNN)NNNNNN)NNNNNNNNNNNNNNN)NNNNNNNNNNNNNN)NNNNNNNNNNNNNNNNNN)NNNNNNNNNNNNNNNNNNN)
NNNNNNNNNN)	NNNNNNNNN)NNNNNNNN)r  NNNNNNNNNNNNN)r   NNNNN)NNNNNNNNNNNNNNNNN)F)NNF)NNNNNNN)r-   r.   r/   r0   r&   r9   r   r   r   r?   rG   rQ   rU   staticmethodr]   r   r  rd   rh   rn   ro   rr   rv   rw   ry   ENCRYPTION_ALGORITHMr{   r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r8   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  objectr   integer_typesr9  rA  rF  rH  rO  rZ  r[  rc  rh  ri  rj  ro  r  r|  r}  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  boolr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r5  r   rX  r  r   r   r  r  r  r7   r$   r$   r$   r%   r1   Y   s   
T$


"*
5`4hFKD*^42 '[6&(%
&_	
,r1   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )SelectMessagez1
    returned message from select object api
    c                 C   s   d| _ || _|| _|| _dS )z/
        Initialize for record message
        RecordsN)typer@   payloadr  )r#   r@   r  r  r$   r$   r%   set_record_messageQ  s   
z SelectMessage.set_record_messagec                 C   s"   d| _ || _|| _|| _|| _dS )z1
        Initialize for continue message
        ContN)r  r@   bytes_scannedbytes_returnedr  )r#   r@   r  r	  r  r$   r$   r%   set_cont_messageZ  s
   
zSelectMessage.set_cont_messagec                 C   s   d| _ || _|| _dS )z,
        Initialize for end message
        EndN)r  r@   r  )r#   r@   r  r$   r$   r%   set_end_messaged  s   
zSelectMessage.set_end_messagec                 C   sD   | j dkrd| j| jS | j dkrd| j| j| jS d| jS )Nr  z{}
{}r  z%{}
bytes_scanned/bytes_returned={}/{}z{})r  r   r@   r  r  r	  r"   r$   r$   r%   __str__l  s   

zSelectMessage.__str__N)r-   r.   r/   r0   r  r
  r  r  r$   r$   r$   r%   r  M  s    	
r  c                   @   s4   e Zd ZdZdd Zdd Zdd Zedd	 Zd
S )r  z0
    deal with message of select object api
    c                 C   s
   d| _ d S r   )finishr"   r$   r$   r%   r&   y  s   
zSelectResponse.__init__c                 C   s   || _ || _dS )z2
        get HttpResponse and BceResponse
        Nr  )r#   r   r>   r$   r$   r%   r  |  s   
z&SelectResponse.init_from_http_responsec                 c   s   | j }z| js|d}|sttd|dd d }td|dd d }||}| |}t }|d dkr`|| d }||}	td|dd }
||t	
|	|
 |V  nh|d dkr|d}|d}td|dd }
td	|d }td	|d }|||||
 |V  n1|d d
krtd|dd }
|d dkrt|d |d | jjjd|||
 d| _|V  | jrW | j   dS | j   w )z-
        generator for SelectMessage
           z>Ir   r  zmessage-typer     r  z>Qr  z
error-codesuccesszerror-message)r  Z
request_idTN)r   r  r  StopIterationstructunpack_parse_select_headersr  r  r   rm   r
  r   r>   r   Zbce_request_idr  r  )r#   r  ZpreludeZ	total_lenZheaders_lenr@   Zheaders_mapmsgZpayload_lenr  r  r  r	  r$   r$   r%   r+     sL   





zSelectResponse.resultc                 C   s   i }d}|t | k rVtd| ||d  d }|d7 }| |||  }||7 }td| ||d  d }|d7 }| |||  }||7 }t||t|< |t | k s
|S )z\
        parse SELECT headers
        :param headers: <str>
        :return: <dict>
        r   Br#  z>Hr   )r   r  r  r   rm   )r@   Zhmrs   Zkey_lenr   Z	value_lenvaluer$   r$   r%   r    s   z$SelectResponse._parse_select_headersN)	r-   r.   r/   r0   r&   r  r+   r  r  r$   r$   r$   r%   r  u  s    )r  )Ar0   r>  r  http.clientrL   rK  rD   loggingr	  r  builtinsr   r   Zfuture.utilsr   r   r   concurrent.futuresr   r   r	   r
   r   	functoolsr  r<  r   r   Zbaidubce.authr   Zbaidubce.bce_base_clientr   Zbaidubce.exceptionr   r   r   Zbaidubce.httpr   r   r   r   r   Zbaidubce.servicesr   Zbaidubce.services.bosr   r   Zbaidubce.utilsr   r   Zbaidubce.protocolr   r   	getLoggerr-   r2  ZFETCH_MODE_SYNCZFETCH_MODE_ASYNCr  r  r   r1   r  r  r  r$   r$   r$   r%   <module>   s   
                          (