o
    MfE                    @   s  d 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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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(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"l2m3Z3 dd#l2m4Z4 dd$l(m5Z5 dd%l(m6Z6 dd&l(m7Z7 dd'l8m9Z9 dd(l8m: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;mAZA dd/l;mBZB dd0lCmDZD dd1lCmEZE dd2lCmFZF dd3lCmGZG dd4lCmHZH dd5lImJZJ dd6lImKZK d7ZLd8ZMd9ZNeNd: ZOeNd; ZPd<ZQd=d>d?d@eQdAdBdCdDdEdFdGfZRdHZSdIZTdJZUdKZVdLZWdMZXdNZYe
ZdOZ[dPZ\dQZ]e^e_Z`G dRdS dSe+ZadTdU ZbdddWdXZcdedZd[Zdddd\d]Zed^d_ Zfd`da ZgG dbdc dcehZidS )fz3Create / interact with Google Cloud Storage blobs.
    N)BytesIO)TextIOWrapper)HeaderParser)	parse_qsl)quote)	urlencode)urlsplit)
urlunsplit)resumable_media)ChunkedDownload)Download)RawDownload)RawChunkedDownload)MultipartUpload)ResumableUpload)Policy)
exceptions)_bytes_to_unicode)_datetime_to_rfc3339)_rfc3339_nanos_to_datetime)	_to_bytes)NotFound)_add_etag_match_headers) _add_generation_match_parameters)_PropertyMixin)_scalar_property)_bucket_bound_hostname_url)_raise_if_more_than_one_set)(_api_core_retry_to_resumable_media_retry)_get_default_headers)_get_default_storage_base_url)generate_signed_url_v2)generate_signed_url_v4)_NUM_RETRIES_MESSAGE)_API_VERSION)_virtual_hosted_style_base_url)ACL)	ObjectACL)_DEFAULT_TIMEOUT)ARCHIVE_STORAGE_CLASS)COLDLINE_STORAGE_CLASS)#MULTI_REGIONAL_LEGACY_STORAGE_CLASS)NEARLINE_STORAGE_CLASS)REGIONAL_LEGACY_STORAGE_CLASS)STANDARD_STORAGE_CLASS)ConditionalRetryPolicy)DEFAULT_RETRY)DEFAULT_RETRY_IF_ETAG_IN_JSON)%DEFAULT_RETRY_IF_GENERATION_SPECIFIED))DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED)
BlobReader)
BlobWriterzapplication/octet-streamz9{hostname}/download/storage/{api_version}{path}?alt=mediazB{hostname}/upload/storage/{api_version}{bucket_path}/o?uploadType=	multipart	resumablecontentTypecacheControlcontentDispositioncontentEncodingcontentLanguagecrc32c
customTimemd5Hashmetadataname	retentionstorageClasszOSize {:d} was specified but the file-like object only had {:d} bytes remaining.znA checksum of type `{}` was requested, but checksumming is not available for downloads when chunk_size is set.z'if_generation_match: type list' is deprecated and supported for backwards-compatability reasons only.  Use 'if_source_generation_match' instead' to match source objects' generations.zUse 'if_generation_match' to match the generation of the destination object by passing in a generation number, instead of a list. Use 'if_source_generation_match' to match source objects generations.z'if_metageneration_match: type list' is deprecated and supported for backwards-compatability reasons only. Note that the metageneration to be matched is that of the destination blob. Please pass in a single value (type long).zH'if_source_generation_match' length must be the same as 'sources' lengthzlBlob.download_as_string() is deprecated and will be removed in future. Use Blob.download_as_bytes() instead.zB(?P<scheme>gs)://(?P<bucket_name>[a-z0-9_.-]+)/(?P<object_name>.+)i  @i   c                       s  e Zd ZdZdZdZ	 eeee	e
efZ	 				d fdd	Zedd Zedd	 Zejd
d	 Zedd Zejdd Zedd Zedd Zdd Zedd Zedd Zedd Zdd Zedd Zedd Zedd d!Z			"													#		$dd%d&Zddddddde e!df
d'd(Z"ddddde e#fd)d*Z$d+d, Z%				dd-d.Z&d/d0 Z'ddd#e d1dfd2d3Z(dddd#dddddde d1e!fd4d5Z)d6d7 Z*dddd#dddddde d1e!fd8d9Z+dddd#dddddde d1e!fd:d;Z,dddd#dddddde e!fd<d=Z-dddd#ddddddde e!fd>d?Z.dd@dAZ/dBdC Z0ddDdEZ1e dddfdFdGZ2ddddddde dddfdHdIZ3e dddfdJdKZ4e dddfdLdMZ5d#ddddddddde de#dfdNdOZ6d#ddddddddde de#fdPdQZ7ddRdSZ8dddddddde de#fdTdUZ9dVddddddde de#fdWdXZ:dddde dddddde#fdYdZZ;dde e!fd[d\Z<de e=fd]d^Z>de e!fd_d`Z?de dddde@fdadbZAde dddde@fdcddZBde ddde#fdedfZCdddddddddde e#fdgdhZDddddddddde e#fdidjZE	k					ddldmZFeGdnZH	 eGdoZI	 eGdpZJ	 eGdqZK	 eGeLZM	 eGdrZN	 dddd#dddddde d1e!dfdsdtZOedudv ZPedwdx ZQeGdyZR	 edzd{ ZSed|d} ZTeGd~ZU	 edd ZVedd ZWeWjdd ZWedd ZXedd ZYedd ZZedd Z[edd Z\edd Z]e]jdd Z]eGdZ^	 eGdZ_	 edd Z`edd Zaedd Zbedd Zcecjdd Zcedd Zdedd Zeedd Zf  ZgS )BlobaY  A wrapper around Cloud Storage's concept of an ``Object``.

    :type name: str
    :param name: The name of the blob.  This corresponds to the unique path of
                 the object in the bucket. If bytes, will be converted to a
                 unicode object. Blob / object names can contain any sequence
                 of valid unicode characters, of length 1-1024 bytes when
                 UTF-8 encoded.

    :type bucket: :class:`google.cloud.storage.bucket.Bucket`
    :param bucket: The bucket to which this blob belongs.

    :type chunk_size: int
    :param chunk_size:
        (Optional) The size of a chunk of data whenever iterating (in bytes).
        This must be a multiple of 256 KB per the API specification. If not
        specified, the chunk_size of the blob itself is used. If that is not
        specified, a default value of 40 MB is used.

    :type encryption_key: bytes
    :param encryption_key:
        (Optional) 32 byte encryption key for customer-supplied encryption.
        See https://cloud.google.com/storage/docs/encryption#customer-supplied.

    :type kms_key_name: str
    :param kms_key_name:
        (Optional) Resource name of Cloud KMS key used to encrypt the blob's
        contents.

    :type generation: long
    :param generation:
        (Optional) If present, selects a specific revision of this object.
    Ni   c                    sn   t |}tt| j|d || _|| _t| | _t||d || _	|dur*|| j
d< |dur5|| j
d< dS dS )zH
        property :attr:`name`
            Get the blob's name.
        rA   )encryption_keykms_key_nameN
kmsKeyName
generation)r   superrD   __init__
chunk_size_bucketr'   _aclr   _encryption_key_properties)selfrA   bucketrL   rF   rG   rI   	__class__ [/var/www/html/analyze/labelStudio/lib/python3.10/site-packages/google/cloud/storage/blob.pyrK      s   

zBlob.__init__c                 C      | j S )zBucket which contains the object.

        :rtype: :class:`~google.cloud.storage.bucket.Bucket`
        :returns: The object's bucket.
        )rM   rQ   rU   rU   rV   rR         zBlob.bucketc                 C   rW   )zGet the blob's default chunk size.

        :rtype: int or ``NoneType``
        :returns: The current blob's chunk size, if it is set.
        )_chunk_sizerX   rU   rU   rV   rL      rY   zBlob.chunk_sizec                 C   s8   |dur|dkr|| j  dkrtd| j f || _dS )a  Set the blob's default chunk size.

        :type value: int
        :param value: (Optional) The current blob's chunk size, if it is set.

        :raises: :class:`ValueError` if ``value`` is not ``None`` and is not a
                 multiple of 256 KB.
        Nr   z$Chunk size must be a multiple of %d.)_CHUNK_SIZE_MULTIPLE
ValueErrorrZ   rQ   valuerU   rU   rV   rL      s
   


c                 C   rW   )a#  Retrieve the customer-supplied encryption key for the object.

        :rtype: bytes or ``NoneType``
        :returns:
            The encryption key or ``None`` if no customer-supplied encryption key was used,
            or the blob's resource has not been loaded from the server.
        rO   rX   rU   rU   rV   rF     s   	zBlob.encryption_keyc                 C   s
   || _ dS )a  Set the blob's encryption key.

        See https://cloud.google.com/storage/docs/encryption#customer-supplied

        To perform a key rotation for an encrypted blob, use :meth:`rewrite`.
        See https://cloud.google.com/storage/docs/encryption/using-customer-supplied-keys?hl=ca#rotating

        :type value: bytes
        :param value: 32 byte encryption key for customer-supplied encryption.
        Nr_   r]   rU   rU   rV   rF     s   
c                 C   s   | d t | S )a  Relative URL path for a blob.

        :type bucket_path: str
        :param bucket_path: The URL path for a bucket.

        :type blob_name: str
        :param blob_name: The name of the blob.

        :rtype: str
        :returns: The relative URL path for ``blob_name``.
        z/o/)_quote)bucket_path	blob_namerU   rU   rV   path_helper(  s   zBlob.path_helperc                 C   rW   )zCreate our ACL on demand.)rN   rX   rU   rU   rV   acl7  s   zBlob.aclc                 C   s0   | j r| j j}nd }d| d| j d| j dS )Nz<Blob: z, >)rR   rA   rI   )rQ   bucket_namerU   rU   rV   __repr__<  s   
zBlob.__repr__c                 C   s    | j std| | jj| j S )zyGetter property for the URL path to this Blob.

        :rtype: str
        :returns: The URL path to this Blob.
        z*Cannot determine path without a blob name.)rA   r\   rc   rR   pathrX   rU   rU   rV   rh   D  s   z	Blob.pathc                 C      | j jS )zThe client bound to this blob.)rR   clientrX   rU   rU   rV   rj   P  s   zBlob.clientc                 C   ri   )zzProject ID billed for API requests made via this blob.

        Derived from bucket's value.

        :rtype: str
        )rR   user_projectrX   rU   rU   rV   rk   U  s   zBlob.user_projectc                 C   s
   t | jS )zReturn any encryption headers needed to fetch the object.

        :rtype: List(Tuple(str, str))
        :returns: a list of tuples to be passed as headers.
        )_get_encryption_headersrO   rX   rU   rU   rV   _encryption_headers_  s   
zBlob._encryption_headersc                 C   s0   i }| j dur| j |d< | jdur| j|d< |S )zDefault query parameters.NrI   userProject)rI   rk   )rQ   paramsrU   rU   rV   _query_paramsg  s   



zBlob._query_paramsc                 C   s4   | j r| j j}nt }dj|| jjt| jdddS )zThe public URL for this blob.

        Use :meth:`make_public` to enable anonymous access via the returned
        URL.

        :rtype: `string`
        :returns: The public URL for this blob.
        z.{storage_base_url}/{bucket_name}/{quoted_name}   /~safe)storage_base_urlrf   quoted_name)rj   api_endpointr    formatrR   rA   r`   )rQ   endpointrU   rU   rV   
public_urlq  s   

zBlob.public_urlc                 C   sD   ddl m} t|}|std|||dd}| |d|S )a  Get a constructor for blob object by URI.

        .. code-block:: python

            from google.cloud import storage
            from google.cloud.storage.blob import Blob
            client = storage.Client()
            blob = Blob.from_string("gs://bucket/object", client=client)

        :type uri: str
        :param uri: The blob uri following a gs://bucket/object pattern.
          Both a bucket and object name is required to construct a blob object.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  Application code should
            *always* pass ``client``.

        :rtype: :class:`google.cloud.storage.blob.Blob`
        :returns: The blob object created.
        r   )Bucketz&URI pattern must be gs://bucket/objectrf   rE   object_name)google.cloud.storage.bucketrz   _GS_URL_REGEX_PATTERNmatchr\   group)clsurirj   rz   r~   rR   rU   rU   rV   from_string  s   
zBlob.from_stringGETFhttpc                 C   s>  |du rd}n|dvrt d|dus|r|rt d|du r'| |}|j}t| jdd}|r=t|| jj}d| }n|rJt||}d| }n
d| jj d| }|du r`| |}|j}|dkrgt	}nt
}| jdurt| j}|	du ryi }	|dkrd	}|| |	|< n|	| |||||| ||||||	|
||d
S )aJ  Generates a signed URL for this blob.

        .. note::

            If you are on Google Compute Engine, you can't generate a signed
            URL using GCE service account.
            If you'd like to be able to generate a signed URL from GCE,
            you can use a standard service account from a JSON file rather
            than a GCE service account.

        If you have a blob that you want to allow access to for a set
        amount of time, you can use this method to generate a URL that
        is only valid within a certain time period.

        See a [code sample](https://cloud.google.com/storage/docs/samples/storage-generate-signed-url-v4#storage_generate_signed_url_v4-python).

        This is particularly useful if you don't want publicly
        accessible blobs, but don't want to require users to explicitly
        log in.

        If ``bucket_bound_hostname`` is set as an argument of :attr:`api_access_endpoint`,
        ``https`` works only if using a ``CDN``.

        :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
        :param expiration:
            Point in time when the signed URL should expire. If a ``datetime``
            instance is passed without an explicit ``tzinfo`` set,  it will be
            assumed to be ``UTC``.

        :type api_access_endpoint: str
        :param api_access_endpoint: (Optional) URI base, for instance
            "https://storage.googleapis.com". If not specified, the client's
            api_endpoint will be used. Incompatible with bucket_bound_hostname.

        :type method: str
        :param method: The HTTP verb that will be used when requesting the URL.

        :type content_md5: str
        :param content_md5:
            (Optional) The MD5 hash of the object referenced by ``resource``.

        :type content_type: str
        :param content_type:
            (Optional) The content type of the object referenced by
            ``resource``.

        :type response_disposition: str
        :param response_disposition:
            (Optional) Content disposition of responses to requests for the
            signed URL.  For example, to enable the signed URL to initiate a
            file of ``blog.png``, use the value ``'attachment;
            filename=blob.png'``.

        :type response_type: str
        :param response_type:
            (Optional) Content type of responses to requests for the signed
            URL. Ignored if content_type is set on object/blob metadata.

        :type generation: str
        :param generation:
            (Optional) A value that indicates which generation of the resource
            to fetch.

        :type headers: dict
        :param headers:
            (Optional) Additional HTTP headers to be included as part of the
            signed URLs. See:
            https://cloud.google.com/storage/docs/xml-api/reference-headers
            Requests using the signed URL *must* pass the specified header
            (name and value) with each request for the URL.

        :type query_parameters: dict
        :param query_parameters:
            (Optional) Additional query parameters to be included as part of the
            signed URLs. See:
            https://cloud.google.com/storage/docs/xml-api/reference-headers#query

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type credentials: :class:`google.auth.credentials.Credentials`
        :param credentials:
            (Optional) The authorization credentials to attach to requests.
            These credentials identify this application to the service.  If
            none are specified, the client will attempt to ascertain the
            credentials from the environment.

        :type version: str
        :param version:
            (Optional) The version of signed credential to create.  Must be one
            of 'v2' | 'v4'.

        :type service_account_email: str
        :param service_account_email:
            (Optional) E-mail address of the service account.

        :type access_token: str
        :param access_token: (Optional) Access token for a service account.

        :type virtual_hosted_style: bool
        :param virtual_hosted_style:
            (Optional) If true, then construct the URL relative the bucket's
            virtual hostname, e.g., '<bucket-name>.storage.googleapis.com'.
            Incompatible with bucket_bound_hostname.

        :type bucket_bound_hostname: str
        :param bucket_bound_hostname:
            (Optional) If passed, then construct the URL relative to the bucket-bound hostname.
            Value can be a bare or with scheme, e.g., 'example.com' or 'http://example.com'.
            Incompatible with api_access_endpoint and virtual_hosted_style.
            See: https://cloud.google.com/storage/docs/request-endpoints#cname

        :type scheme: str
        :param scheme:
            (Optional) If ``bucket_bound_hostname`` is passed as a bare
            hostname, use this value as the scheme.  ``https`` will work only
            when using a CDN.  Defaults to ``"http"``.

        :raises: :exc:`ValueError` when version is invalid or mutually exclusive arguments are used.
        :raises: :exc:`TypeError` when expiration is not a valid type.
        :raises: :exc:`AttributeError` if credentials is not an instance
                of :class:`google.auth.credentials.Signing`.

        :rtype: str
        :returns: A signed URL you can use to access the resource
                  until expiration.
        Nv2)r   v4z%'version' must be either 'v2' or 'v4'zmThe bucket_bound_hostname argument is not compatible with either api_access_endpoint or virtual_hosted_style.rq   rr   /zX-Goog-Encryption-Algorithm)resource
expirationapi_access_endpointmethodcontent_md5content_typeresponse_typeresponse_dispositionrI   headersquery_parametersservice_account_emailaccess_token)r\   _require_clientrv   r`   rA   r%   rR   r   _credentialsr!   r"   rO   rl   updateupper)rQ   r   r   r   r   r   r   r   rI   r   r   rj   credentialsversionr   r   virtual_hosted_stylebucket_bound_hostnameschemeru   r   helperencryption_headersv2_copy_onlyrU   rU   rV   generate_signed_url  sp    




zBlob.generate_signed_urlc                 C   s   |  |}| j}d|d< |
dur|
|d< t|||||d i }t|||d z|j| j||||	dd W d	S  ty?   Y dS w )
aC  Determines whether or not this blob exists.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match:
            (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]]
        :param if_etag_not_match:
            (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :type soft_deleted: bool
        :param soft_deleted:
            (Optional) If True, looks for a soft-deleted object. Will only return True
            if the object exists and is in a soft-deleted state.
            :attr:`generation` is required to be set on the blob if ``soft_deleted`` is set to True.
            See: https://cloud.google.com/storage/docs/soft-delete

        :rtype: bool
        :returns: True if the blob exists in Cloud Storage.
        rA   fieldsNsoftDeletedif_generation_matchif_generation_not_matchif_metageneration_matchif_metageneration_not_matchif_etag_matchif_etag_not_matchquery_paramsr   timeoutretry_target_objectFT)r   rp   r   r   _get_resourcerh   r   )rQ   rj   r   r   r   r   r   r   r   r   soft_deletedr   r   rU   rU   rV   exists  s:   
BzBlob.existsc                 C   s&   | j j| j|| j||||||d	 dS )a  Deletes a blob from Cloud Storage.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use. If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :raises: :class:`google.cloud.exceptions.NotFound`
                 (propagated from
                 :meth:`google.cloud.storage.bucket.Bucket.delete_blob`).
        )rj   rI   r   r   r   r   r   r   N)rR   delete_blobrA   rI   )rQ   rj   r   r   r   r   r   r   rU   rU   rV   delete  s   1
zBlob.deletec                 C   s   |  |}|jS )a  Return the client's transport.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :rtype transport:
            :class:`~google.auth.transport.requests.AuthorizedSession`
        :returns: The transport (with credentials) that will
                  make authenticated requests.
        )r   _http)rQ   rj   rU   rU   rV   _get_transport(  s   
zBlob._get_transportc           	      C   s   g }| j du r%t|j}tj|| jtd}| jdur$|d| jdf n| j }| j	dur5|d| j	f t
|||||d t||S )a  Get the download URL for the current blob.

        If the ``media_link`` has been loaded, it will be used, otherwise
        the URL will be constructed from the current blob's path (and possibly
        generation) to avoid a round trip.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client: The client to use.

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :rtype: str
        :returns: The download URL for the current blob.
        N)hostnamerh   api_versionrI   drn   r   )
media_link_get_host_name_connection_DOWNLOAD_URL_TEMPLATErw   rh   r$   rI   appendrk   r   _add_query_parameters)	rQ   rj   r   r   r   r   name_value_pairsr   base_urlrU   rU   rV   _get_download_url8  s(   $




zBlob._get_download_urlc                 C   s  |j dd| jd< |j dd| jt< |j dd| jd< |j dd| jd< |j d	d| jd
< |j dd| jd< |j dd| jd< |j dd| jd< |j dd}|ri }|dD ]}td|}|rt| \}}|||< q`|dd| jd< |dd| jd< dS dS )a2  Extract headers from a non-chunked request's http object.

        This avoids the need to make a second request for commonly used
        headers.

        :type response:
            :class requests.models.Response
        :param response: The server response from downloading a non-chunked file
        zContent-EncodingNr;   zContent-TypezCache-Controlr9   zX-Goog-Storage-ClassrC   zContent-Languager<   ETagetagzX-goog-generationrI   zX-goog-metagenerationmetagenerationzX-Goog-Hash ,z (crc32c|md5)=([\w\d/\+/]+={0,3})r=   md5r?   )r   getrP   _CONTENT_TYPE_FIELDsplitrer~   groups)rQ   responsex_goog_hashdigestsencoded_digestr~   r   digestrU   rU   rV   _extract_headers_from_downloads  s<   





z#Blob._extract_headers_from_downloadr   c                 C   s   t |
}| jdu r+|rt}nt}|||||||	d}||_|j||d}| | dS |	r7t|	}t	
| |r<t}nt}||| j|||rH|nd|d}||_|js_|j||d |jrSdS dS )af
  Perform a download without any error handling.

        This is intended to be called by :meth:`_prep_and_do_download` so it can
        be wrapped with error handling / remapping.

        :type transport:
            :class:`~google.auth.transport.requests.AuthorizedSession`
        :param transport:
            The transport (with credentials) that will make authenticated
            requests.

        :type file_obj: file
        :param file_obj: A file handle to which to write the blob's data.

        :type download_url: str
        :param download_url: The URL where the media can be accessed.

        :type headers: dict
        :param headers: Headers to be sent with the request(s).

        :type start: int
        :param start: (Optional) The first byte in a range to be downloaded.

        :type end: int
        :param end: (Optional) The last byte in a range to be downloaded.

        :type raw_download: bool
        :param raw_download:
            (Optional) If true, download the object without any expansion.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify the integrity
            of the object. The response headers must contain a checksum of the
            requested type. If the headers lack an appropriate checksum (for
            instance in the case of transcoded or ranged downloads where the
            remote service does not know the correct checksum, including
            downloads where chunk_size is set) an INFO-level log will be
            emitted. Supported values are "md5", "crc32c" and None. The default
            is "md5".

        :type retry: google.api_core.retry.Retry
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will configure backoff and timeout options. Custom
            predicates (customizable error codes) are not supported for media
            operations such as this one.

            This private method does not accept ConditionalRetryPolicy values
            because the information necessary to evaluate the policy is instead
            evaluated in blob._prep_and_do_download().

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.
        N)streamr   startendchecksumr   r   )r   r   r   )r   rL   r   r   _retry_strategyconsumer   "_CHUNKED_DOWNLOAD_CHECKSUM_MESSAGErw   _loggerinfor   r   finishedconsume_next_chunk)rQ   	transportfile_objdownload_urlr   r   r   raw_downloadr   r   r   retry_strategyklassdownloadr   msgrU   rU   rV   _do_download  sD   K



	zBlob._do_downloadc                 C   *   | j |||||||||	|
||||d dS )a  Download the contents of this blob into a file-like object.

        .. note::

           If the server-set property, :attr:`media_link`, is not yet
           initialized, makes an additional API request to load it.

        If the :attr:`chunk_size` of a current blob is `None`, will download data
        in single download request otherwise it will download the :attr:`chunk_size`
        of data in each request.

        For more fine-grained control over the download process, check out
        [`google-resumable-media`](https://googleapis.dev/python/google-resumable-media/latest/index.html).
        For example, this library allows downloading **parts** of a blob rather than the whole thing.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type file_obj: file
        :param file_obj: A file handle to which to write the blob's data.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type start: int
        :param start: (Optional) The first byte in a range to be downloaded.

        :type end: int
        :param end: (Optional) The last byte in a range to be downloaded.

        :type raw_download: bool
        :param raw_download:
            (Optional) If true, download the object without any expansion.

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match:
            (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]]
        :param if_etag_not_match:
            (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify the integrity
            of the object. The response headers must contain a checksum of the
            requested type. If the headers lack an appropriate checksum (for
            instance in the case of transcoded or ranged downloads where the
            remote service does not know the correct checksum, including
            downloads where chunk_size is set) an INFO-level log will be
            emitted. Supported values are "md5", "crc32c" and None. The default
            is "md5".

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_metageneration_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :raises: :class:`google.cloud.exceptions.NotFound`
        rj   r   r   r   r   r   r   r   r   r   r   r   r   N)_prep_and_do_download)rQ   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   rU   rU   rV   download_to_file  s    v
zBlob.download_to_filec                 O   s   z#t |d}| j|g|R i | W d   n1 sw   Y  W n tjy1   t|  w | j}|durH| }t|j	||f dS dS )a  Download the contents of this blob into a named file.

        :type filename: str
        :param filename: A filename to be passed to ``open``.

        For *args and **kwargs, refer to the documentation for download_to_filename() for more information.
        wbN)
openr   r
   DataCorruptionosremoveupdated	timestamputimerA   )rQ   filenameargskwargsr   r   mtimerU   rU   rV   _handle_filename_and_download  s(   	
z"Blob._handle_filename_and_downloadc                 C   r   )a.  Download the contents of this blob into a named file.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        See a [code sample](https://cloud.google.com/storage/docs/samples/storage-download-encrypted-file#storage_download_encrypted_file-python)
        to download a file with a [`customer-supplied encryption key`](https://cloud.google.com/storage/docs/encryption#customer-supplied).

        :type filename: str
        :param filename: A filename to be passed to ``open``.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use. If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type start: int
        :param start: (Optional) The first byte in a range to be downloaded.

        :type end: int
        :param end: (Optional) The last byte in a range to be downloaded.

        :type raw_download: bool
        :param raw_download:
            (Optional) If true, download the object without any expansion.

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match:
            (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]]
        :param if_etag_not_match:
            (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify the integrity
            of the object. The response headers must contain a checksum of the
            requested type. If the headers lack an appropriate checksum (for
            instance in the case of transcoded or ranged downloads where the
            remote service does not know the correct checksum, including
            downloads where chunk_size is set) an INFO-level log will be
            emitted. Supported values are "md5", "crc32c" and None. The default
            is "md5".

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_metageneration_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :raises: :class:`google.cloud.exceptions.NotFound`
        r   N)r   )rQ   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   rU   rU   rV   download_to_filename  s    l
zBlob.download_to_filenamec                 C   s4   t  }| j||||||||||	|
|||d | S )a  Download the contents of this blob as a bytes object.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use. If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type start: int
        :param start: (Optional) The first byte in a range to be downloaded.

        :type end: int
        :param end: (Optional) The last byte in a range to be downloaded.

        :type raw_download: bool
        :param raw_download:
            (Optional) If true, download the object without any expansion.

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match:
            (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]]
        :param if_etag_not_match:
            (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify the integrity
            of the object. The response headers must contain a checksum of the
            requested type. If the headers lack an appropriate checksum (for
            instance in the case of transcoded or ranged downloads where the
            remote service does not know the correct checksum, including
            downloads where chunk_size is set) an INFO-level log will be
            emitted. Supported values are "md5", "crc32c" and None. The default
            is "md5".

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_metageneration_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :rtype: bytes
        :returns: The data stored in this blob.

        :raises: :class:`google.cloud.exceptions.NotFound`
        r   )r   r   getvalue)rQ   rj   r   r   r   r   r   r   r   r   r   r   r   r   string_bufferrU   rU   rV   download_as_bytes1  s$   hzBlob.download_as_bytesc                 C   s2   t jttdd | j|||||||||	|
||dS )a  (Deprecated) Download the contents of this blob as a bytes object.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        .. note::
           Deprecated alias for :meth:`download_as_bytes`.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use. If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type start: int
        :param start: (Optional) The first byte in a range to be downloaded.

        :type end: int
        :param end: (Optional) The last byte in a range to be downloaded.

        :type raw_download: bool
        :param raw_download:
            (Optional) If true, download the object without any expansion.

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match:
            (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]]
        :param if_etag_not_match:
            (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_metageneration_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :rtype: bytes
        :returns: The data stored in this blob.

        :raises: :class:`google.cloud.exceptions.NotFound`
           
stacklevelrj   r   r   r   r   r   r   r   r   r   r   r   )warningswarn_DOWNLOAD_AS_STRING_DEPRECATEDPendingDeprecationWarningr   )rQ   rj   r   r   r   r   r   r   r   r   r   r   r   rU   rU   rV   download_as_string  s"   ^zBlob.download_as_stringc                 C   s   | j ||||||||	|
|||d}|dur||S | jdur=t d| j }t| dd }d|v r=||d S |dS )aI  Download the contents of this blob as text (*not* bytes).

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use. If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type start: int
        :param start: (Optional) The first byte in a range to be downloaded.

        :type end: int
        :param end: (Optional) The last byte in a range to be downloaded.

        :type raw_download: bool
        :param raw_download:
            (Optional) If true, download the object without any expansion.

        :type encoding: str
        :param encoding: (Optional) encoding to be used to decode the
            downloaded bytes.  Defaults to the ``charset`` param of
            attr:`content_type`, or else to "utf-8".

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match:
            (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]]
        :param if_etag_not_match:
            (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_metageneration_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :rtype: text
        :returns: The data stored in this blob, decoded to text.
        r  NzContent-Type:    charsetutf-8)r   decoder   r   parsestrdict
get_params)rQ   rj   r   r   r   encodingr   r   r   r   r   r   r   r   datar   ro   rU   rU   rV   download_as_text  s,   _


zBlob.download_as_textc                 C   s<   |du r| j }|du r|durt|\}}|du rt}|S )aW  Determine the content type from the current object.

        The return value will be determined in order of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        :type content_type: str
        :param content_type: (Optional) Type of content.

        :type filename: str
        :param filename:
            (Optional) The name of the file where the content is stored.

        :rtype: str
        :returns: Type of content gathered from the object.
        N)r   	mimetypes
guess_type_DEFAULT_CONTENT_TYPE)rQ   r   r   _rU   rU   rV   _get_content_type  s   zBlob._get_content_typec                 C   s0   d| j i}| jD ]}|tv r| j| ||< q|S )a  Get the object / blob metadata which is writable.

        This is intended to be used when creating a new object / blob.

        See the [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects)
        for more information, the fields marked as writable are:

        * ``acl``
        * ``cacheControl``
        * ``contentDisposition``
        * ``contentEncoding``
        * ``contentLanguage``
        * ``contentType``
        * ``crc32c``
        * ``customTime``
        * ``md5Hash``
        * ``metadata``
        * ``name``
        * ``retention``
        * ``storageClass``

        For now, we don't support ``acl``, access control lists should be
        managed directly through :class:`ObjectACL` methods.
        rA   )rA   _changes_WRITABLE_FIELDSrP   )rQ   object_metadatakeyrU   rU   rV   _get_writable_metadata  s   

zBlob._get_writable_metadatac                 C   sF   | j ||d}i t|jj||dt| j|j}|  }|||fS )a|  Get required arguments for performing an upload.

        The content type returned will be determined in order of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        :type content_type: str
        :param content_type: Type of content being uploaded (or :data:`None`).

        :type command: str
        :param command:
            (Optional) Information about which interface for upload was used,
            to be included in the X-Goog-API-Client header. Please leave as None
            unless otherwise directed.

        :rtype: tuple
        :returns: A triple of

                  * A header dictionary
                  * An object metadata dictionary
                  * The ``content_type`` as a string (according to precedence)
        r   command)r  r   r   
user_agentrl   rO   _extra_headersr  )rQ   rj   r   r   r  r   r  rU   rU   rV   _get_upload_arguments  s   

zBlob._get_upload_argumentsc                 C   s  |du r	|  }n| |}t||k r t|t|}t|| |}| |}d| jv r:d| jvr:| j	d | j
|||d}|\}}}t|j}tj|| jjtd}g }| jdure|d| jf | jdurwd| jvrw|d| jf |dur|d|f |dur|d	|f |dur|d
|f |	dur|d|	f |
dur|d|
f t||}t|||d}t|||_|j|||||d}|S )a  Perform a multipart upload.

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type stream: IO[bytes]
        :param stream: A bytes IO object open for reading.

        :type content_type: str
        :param content_type: Type of content being uploaded (or :data:`None`).

        :type size: int
        :param size:
            The number of bytes to be uploaded (which will be read from
            ``stream``). If not provided, the upload will be concluded once
            ``stream`` is exhausted (or :data:`None`).

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. The request metadata will be amended
            to include the computed value. Using this option will override a
            manually-set checksum value. Supported values are "md5",
            "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will configure backoff and timeout options. Custom
            predicates (customizable error codes) are not supported for media
            operations such as this one.

            This private method does not accept ConditionalRetryPolicy values
            because the information necessary to evaluate the policy is instead
            evaluated in blob._do_upload().

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

        :type command: str
        :param command:
            (Optional) Information about which interface for upload was used,
            to be included in the X-Goog-API-Client header. Please leave as None
            unless otherwise directed.

        :rtype: :class:`~requests.Response`
        :returns: The "200 OK" response object returned after the multipart
                  upload request.
        :raises: :exc:`ValueError` if ``size`` is not :data:`None` but the
                 ``stream`` has fewer than ``size`` bytes remaining.
        Nr@   r  r   ra   r   rn   cryptoKeyVersionsrH   predefinedAclifGenerationMatchifGenerationNotMatchifMetagenerationMatchifMetaGenerationNotMatchr   r   r   )readlen_READ_LESS_THAN_SIZErw   r\   r   r   rP   r  addr   r   r   _MULTIPART_URL_TEMPLATErR   rh   r$   rk   r   rG   r   r   r   r   transmit)rQ   rj   r   r   sizenum_retriespredefined_aclr   r   r   r   r   r   r   r  r  r   r   r   r   r  r   r   r   
upload_urluploadr   rU   rU   rV   _do_multipart_upload  sV   o











zBlob._do_multipart_uploadc              	   C   s  |  |}|du r| j}|du rt}| |}d| jv r'd| jvr'| jd | j|||d}|\}}}|dur=|| t	|j
}tj|| jjtd}g }| jdur[|d| jf | jdurmd| jvrm|d| jf |durx|d|f |	dur|d	|	f |
dur|d
|
f |dur|d|f |dur|d|f t||}t||||d}t|||_|j|||||d|d ||fS )a  Initiate a resumable upload.

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type stream: IO[bytes]
        :param stream: A bytes IO object open for reading.

        :type content_type: str
        :param content_type: Type of content being uploaded (or :data:`None`).

        :type size: int
        :param size:
            The number of bytes to be uploaded (which will be read from
            ``stream``). If not provided, the upload will be concluded once
            ``stream`` is exhausted (or :data:`None`).

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type extra_headers: dict
        :param extra_headers:
            (Optional) Extra headers to add to standard headers.

        :type chunk_size: int
        :param chunk_size:
            (Optional) Chunk size to use when creating a
            :class:`~google.resumable_media.requests.ResumableUpload`.
            If not passed, will fall back to the chunk size on the
            current blob, if the chunk size of a current blob is also
            `None`, will set the default value.
            The default value of ``chunk_size`` is 100 MB.

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. After the upload is complete, the
            server-computed checksum of the resulting object will be checked
            and google.resumable_media.common.DataCorruption will be raised on
            a mismatch. On a validation failure, the client will attempt to
            delete the uploaded object automatically. Supported values
            are "md5", "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will configure backoff and timeout options. Custom
            predicates (customizable error codes) are not supported for media
            operations such as this one.

            This private method does not accept ConditionalRetryPolicy values
            because the information necessary to evaluate the policy is instead
            evaluated in blob._do_upload().

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

        :type command: str
        :param command:
            (Optional) Information about which interface for upload was used,
            to be included in the X-Goog-API-Client header. Please leave as None
            unless otherwise directed.

        :rtype: tuple
        :returns:
            Pair of

            * The :class:`~google.resumable_media.requests.ResumableUpload`
              that was created
            * The ``transport`` used to initiate the upload.
        Nr@   r  r!  rn   r"  rH   r#  r$  r%  r&  r'  r(  F)total_bytesstream_finalr   )r   rL   _DEFAULT_CHUNKSIZEr   rP   r  r,  r   r   r   r   _RESUMABLE_URL_TEMPLATErw   rR   rh   r$   rk   r   rG   r   r   r   r   initiate)rQ   rj   r   r   r/  r0  r1  extra_headersrL   r   r   r   r   r   r   r   r  r   r   r   r  r   r   r   r2  r3  rU   rU   rV   _initiate_resumable_upload  sh    










zBlob._initiate_resumable_uploadc                 C   sh   | j |||||||||	|
||||d\}}|js2z	|j||d}W n tjy.   |    w |jr|S )a  Perform a resumable upload.

        Assumes ``chunk_size`` is not :data:`None` on the current blob.
        The default value of ``chunk_size`` is 100 MB.

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type stream: IO[bytes]
        :param stream: A bytes IO object open for reading.

        :type content_type: str
        :param content_type: Type of content being uploaded (or :data:`None`).

        :type size: int
        :param size:
            The number of bytes to be uploaded (which will be read from
            ``stream``). If not provided, the upload will be concluded once
            ``stream`` is exhausted (or :data:`None`).

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. After the upload is complete, the
            server-computed checksum of the resulting object will be checked
            and google.resumable_media.common.DataCorruption will be raised on
            a mismatch. On a validation failure, the client will attempt to
            delete the uploaded object automatically. Supported values
            are "md5", "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will configure backoff and timeout options. Custom
            predicates (customizable error codes) are not supported for media
            operations such as this one.

            This private method does not accept ConditionalRetryPolicy values
            because the information necessary to evaluate the policy is instead
            evaluated in blob._do_upload().

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

        :type command: str
        :param command:
            (Optional) Information about which interface for upload was used,
            to be included in the X-Goog-API-Client header. Please leave as None
            unless otherwise directed.

        :rtype: :class:`~requests.Response`
        :returns: The "200 OK" response object returned after the final chunk
                  is uploaded.
        )	r1  r   r   r   r   r   r   r   r  r   )r;  r   transmit_next_chunkr
   r   r   )rQ   rj   r   r   r/  r0  r1  r   r   r   r   r   r   r   r  r3  r   r   rU   rU   rV   _do_resumable_uploadt  s2   r
zBlob._do_resumable_uploadc                 C   s   t |tr||	d}|j|d}|dur/|tkr/| j|||||||||	|
||||d}| S | j|||||||||	|
||||d}| S )a  Determine an upload strategy and then perform the upload.

        If the size of the data to be uploaded exceeds 8 MB a resumable media
        request will be used, otherwise the content and the metadata will be
        uploaded in a single multipart upload request.

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type stream: IO[bytes]
        :param stream: A bytes IO object open for reading.

        :type content_type: str
        :param content_type: Type of content being uploaded (or :data:`None`).

        :type size: int
        :param size:
            The number of bytes to be uploaded (which will be read from
            ``stream``). If not provided, the upload will be concluded once
            ``stream`` is exhausted (or :data:`None`).

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. If the upload is completed in a single
            request, the checksum will be entirely precomputed and the remote
            server will handle verification and error handling. If the upload
            is too large and must be transmitted in multiple requests, the
            checksum will be incrementally computed and the client will handle
            verification and error handling, raising
            google.resumable_media.common.DataCorruption on a mismatch and
            attempting to delete the corrupted file. Supported values are
            "md5", "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_generation_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :type command: str
        :param command:
            (Optional) Information about which interface for upload was used,
            to be included in the X-Goog-API-Client header. Please leave as None
            unless otherwise directed.

        :rtype: dict
        :returns: The parsed JSON from the "200 OK" response. This will be the
                  **only** response in the multipart case and it will be the
                  **final** response in the resumable case.
        r$  r&  r   Nr   r   r   r  )
isinstancer/   "get_retry_policy_if_conditions_met_MAX_MULTIPART_SIZEr4  r=  json)rQ   rj   r   r   r/  r0  r1  r   r   r   r   r   r   r   r  r   r   rU   rU   rV   
_do_upload  sR    
"zBlob._do_uploadc                 C   s   |durt jttdd |tu rd}t||d t|}z| j||||||||	|
|||||d}| 	| W dS  t
jyP } zt| W Y d}~dS d}~ww )aH  Upload the contents of this blob from a file-like object.

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        .. note::
           The effect of uploading to an existing blob depends on the
           "versioning" and "lifecycle" policies defined on the blob's
           bucket.  In the absence of those policies, upload will
           overwrite any existing contents.

           See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning)
           and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle)
           API documents for details.

        If the size of the data to be uploaded exceeds 8 MB a resumable media
        request will be used, otherwise the content and the metadata will be
        uploaded in a single multipart upload request.

        For more fine-grained over the upload process, check out
        [`google-resumable-media`](https://googleapis.dev/python/google-resumable-media/latest/index.html).

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type file_obj: file
        :param file_obj: A file handle opened in binary mode for reading.

        :type rewind: bool
        :param rewind:
            If True, seek to the beginning of the file handle before writing
            the file to Cloud Storage.

        :type size: int
        :param size:
            The number of bytes to be uploaded (which will be read from
            ``file_obj``). If not provided, the upload will be concluded once
            ``file_obj`` is exhausted.

        :type content_type: str
        :param content_type: (Optional) Type of content being uploaded.

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. If the upload is completed in a single
            request, the checksum will be entirely precomputed and the remote
            server will handle verification and error handling. If the upload
            is too large and must be transmitted in multiple requests, the
            checksum will be incrementally computed and the client will handle
            verification and error handling, raising
            google.resumable_media.common.DataCorruption on a mismatch and
            attempting to delete the corrupted file. Supported values are
            "md5", "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_generation_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :type command: str
        :param command:
            (Optional) Information about which interface for upload was used,
            to be included in the X-Goog-API-Client header. Please leave as None
            unless otherwise directed.

        :raises: :class:`~google.cloud.exceptions.GoogleCloudError`
                 if the upload response returns an error status.
        Nr   r   )rewindr@  )r  r  r#   DeprecationWarningr2   _maybe_rewindr&   validate_predefinedrE  _set_propertiesr
   InvalidResponse_raise_from_invalid_response)rQ   r   rF  r/  r   r0  rj   r1  r   r   r   r   r   r   r   r  created_jsonexcrU   rU   rV   _prep_and_do_upload	  s:    
zBlob._prep_and_do_uploadc                 C   r   )aN  Upload the contents of this blob from a file-like object.

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        .. note::
           The effect of uploading to an existing blob depends on the
           "versioning" and "lifecycle" policies defined on the blob's
           bucket.  In the absence of those policies, upload will
           overwrite any existing contents.

           See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning)
           and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle)
           API documents for details.

        If the size of the data to be uploaded exceeds 8 MB a resumable media
        request will be used, otherwise the content and the metadata will be
        uploaded in a single multipart upload request.

        For more fine-grained over the upload process, check out
        [`google-resumable-media`](https://googleapis.dev/python/google-resumable-media/latest/index.html).

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type file_obj: file
        :param file_obj: A file handle opened in binary mode for reading.

        :type rewind: bool
        :param rewind:
            If True, seek to the beginning of the file handle before writing
            the file to Cloud Storage.

        :type size: int
        :param size:
            The number of bytes to be uploaded (which will be read from
            ``file_obj``). If not provided, the upload will be concluded once
            ``file_obj`` is exhausted.

        :type content_type: str
        :param content_type: (Optional) Type of content being uploaded.

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. If the upload is completed in a single
            request, the checksum will be entirely precomputed and the remote
            server will handle verification and error handling. If the upload
            is too large and must be transmitted in multiple requests, the
            checksum will be incrementally computed and the client will handle
            verification and error handling, raising
            google.resumable_media.common.DataCorruption on a mismatch and
            attempting to delete the corrupted file. Supported values are
            "md5", "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_generation_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :raises: :class:`~google.cloud.exceptions.GoogleCloudError`
                 if the upload response returns an error status.
        )rF  r/  r   r0  rj   r1  r   r   r   r   r   r   r   N)rO  )rQ   r   rF  r/  r   r0  rj   r1  r   r   r   r   r   r   r   rU   rU   rV   upload_from_filea
  s"    
zBlob.upload_from_filec                 O   sl   | j ||d}t|d }t| j}| j|g|R ||d| W d   dS 1 s/w   Y  dS )ah  Upload this blob's contents from the content of a named file.

        :type filename: str
        :param filename: The path to the file.

        :type content_type: str
        :param content_type: (Optional) Type of content being uploaded.

        For *args and **kwargs, refer to the documentation for upload_from_filename() for more information.
        r  rb)r   r/  N)r  r   r   fstatfilenost_sizerO  )rQ   r   r   r   r   r   r5  rU   rU   rV   _handle_filename_and_upload
  s   "z Blob._handle_filename_and_uploadc                 C   s&   | j |||||||||	|
||d dS )a  Upload this blob's contents from the content of a named file.

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The value given by ``mimetypes.guess_type``
        - The default value ('application/octet-stream')

        .. note::
           The effect of uploading to an existing blob depends on the
           "versioning" and "lifecycle" policies defined on the blob's
           bucket.  In the absence of those policies, upload will
           overwrite any existing contents.

           See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning)
           and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle)
           API documents for details.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        See a [code sample](https://cloud.google.com/storage/docs/samples/storage-upload-encrypted-file#storage_upload_encrypted_file-python)
        to upload a file with a
        [`customer-supplied encryption key`](https://cloud.google.com/storage/docs/encryption#customer-supplied).

        :type filename: str
        :param filename: The path to the file.

        :type content_type: str
        :param content_type: (Optional) Type of content being uploaded.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. If the upload is completed in a single
            request, the checksum will be entirely precomputed and the remote
            server will handle verification and error handling. If the upload
            is too large and must be transmitted in multiple requests, the
            checksum will be incrementally computed and the client will handle
            verification and error handling, raising
            google.resumable_media.common.DataCorruption on a mismatch and
            attempting to delete the corrupted file. Supported values are
            "md5", "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_generation_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.
        )r   r0  rj   r1  r   r   r   r   r   r   r   N)rU  )rQ   r   r   r0  rj   r1  r   r   r   r   r   r   r   rU   rU   rV   upload_from_filename  s   z
zBlob.upload_from_filenamez
text/plainc                 C   s@   t |dd}t|}| j|t|||||||||	|
||d dS )a  Upload contents of this blob from the provided string.

        .. note::
           The effect of uploading to an existing blob depends on the
           "versioning" and "lifecycle" policies defined on the blob's
           bucket.  In the absence of those policies, upload will
           overwrite any existing contents.

           See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning)
           and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle)
           API documents for details.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type data: bytes or str
        :param data:
            The data to store in this blob.  If the value is text, it will be
            encoded as UTF-8.

        :type content_type: str
        :param content_type:
            (Optional) Type of content being uploaded. Defaults to
            ``'text/plain'``.

        :type num_retries: int
        :param num_retries:
            Number of upload retries. By default, only uploads with
            if_generation_match set will be retried, as uploads without the
            argument are not guaranteed to be idempotent. Setting num_retries
            will override this default behavior and guarantee retries even when
            if_generation_match is not set.  (Deprecated: This argument
            will be removed in a future release.)

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. If the upload is completed in a single
            request, the checksum will be entirely precomputed and the remote
            server will handle verification and error handling. If the upload
            is too large and must be transmitted in multiple requests, the
            checksum will be incrementally computed and the client will handle
            verification and error handling, raising
            google.resumable_media.common.DataCorruption on a mismatch and
            attempting to delete the corrupted file. Supported values are
            "md5", "crc32c" and None. The default is None.

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_generation_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.
        r	  r  )r   r/  r   r0  rj   r1  r   r   r   r   r   r   r   N)r   r   rP  r*  )rQ   r  r   r0  rj   r1  r   r   r   r   r   r   r   r   rU   rU   rV   upload_from_string  s"   q
zBlob.upload_from_stringc                 C   s   t |tr||
d}|j|d}i }|dur||d< ztd}| j||||d|||	|
||| j|||d\}}|jW S  tjyQ } zt	| W Y d}~dS d}~ww )a  Create a resumable upload session.

        Resumable upload sessions allow you to start an upload session from
        one client and complete the session in another. This method is called
        by the initiator to set the metadata and limits. The initiator then
        passes the session URL to the client that will upload the binary data.
        The client performs a PUT request on the session URL to complete the
        upload. This process allows untrusted clients to upload to an
        access-controlled bucket.

        For more details, see the
        documentation on [`signed URLs`](https://cloud.google.com/storage/docs/access-control/signed-urls#signing-resumable).

        The content type of the upload will be determined in order
        of precedence:

        - The value passed in to this method (if not :data:`None`)
        - The value stored on the current blob
        - The default value ('application/octet-stream')

        .. note::
           The effect of uploading to an existing blob depends on the
           "versioning" and "lifecycle" policies defined on the blob's
           bucket.  In the absence of those policies, upload will
           overwrite any existing contents.

           See the [`object versioning`](https://cloud.google.com/storage/docs/object-versioning)
           and [`lifecycle`](https://cloud.google.com/storage/docs/lifecycle)
           API documents for details.

        If :attr:`encryption_key` is set, the blob will be encrypted with
        a [`customer-supplied`](https://cloud.google.com/storage/docs/encryption#customer-supplied)
        encryption key.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type size: int
        :param size:
            (Optional) The maximum number of bytes that can be uploaded using
            this session. If the size is not known when creating the session,
            this should be left blank.

        :type content_type: str
        :param content_type: (Optional) Type of content being uploaded.

        :type origin: str
        :param origin:
            (Optional) If set, the upload can only be completed by a user-agent
            that uploads from the given origin. This can be useful when passing
            the session to a web client.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify
            the integrity of the object. After the upload is complete, the
            server-computed checksum of the resulting object will be checked
            and google.resumable_media.common.DataCorruption will be raised on
            a mismatch. On a validation failure, the client will attempt to
            delete the uploaded object automatically. Supported values
            are "md5", "crc32c" and None. The default is None.

        :type predefined_acl: str
        :param predefined_acl: (Optional) Predefined access control list

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.
            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_generation_match is set.
            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.
            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :rtype: str
        :returns: The resumable upload session URL. The upload can be
                  completed by making an HTTP PUT request with the
                  file's contents.

        :raises: :class:`google.cloud.exceptions.GoogleCloudError`
                 if the session creation response returns an error status.
        r>  r?  NOrigin    )
r1  r   r   r   r   r:  rL   r   r   r   )
rA  r/   rB  r   r;  r[   resumable_urlr
   rK  rL  )rQ   r   r/  originrj   r   r   r1  r   r   r   r   r   r   r:  fake_streamr3  r  rN  rU   rU   rV   create_resumable_upload_session!  sB    

z$Blob.create_resumable_upload_sessionc                 C   sX   |  |}i }| jdur| j|d< |dur||d< |j| j d|||dd}t|S )a  Retrieve the IAM policy for the object.

        .. note::

           Blob- / object-level IAM support does not yet exist and methods
           currently call an internal ACL backend not providing any utility
           beyond the blob's :attr:`acl` at this time. The API may be enhanced
           in the future and is currently undocumented. Use :attr:`acl` for
           managing object access control.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the current object's bucket.

        :type requested_policy_version: int or ``NoneType``
        :param requested_policy_version:
            (Optional) The version of IAM policies to request.  If a policy
            with a condition is requested without setting this, the server will
            return an error.  This must be set to a value of 3 to retrieve IAM
            policies containing conditions. This is to prevent client code that
            isn't aware of IAM conditions from interpreting and modifying
            policies incorrectly.  The service might return a policy with
            version lower than the one that was requested, based on the feature
            syntax in the policy fetched.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :rtype: :class:`google.api_core.iam.Policy`
        :returns: the policy instance, based on the resource returned from
                  the ``getIamPolicy`` API request.
        Nrn   optionsRequestedPolicyVersion/iamr   r   r   r   )r   rk   r   rh   r   from_api_repr)rQ   rj   requested_policy_versionr   r   r   r   rU   rU   rV   get_iam_policy  s   
1



zBlob.get_iam_policyc           	      C   s`   |  |}i }| jdur| j|d< | j d}| }| j|d< |j|||||dd}t|S )a  Update the IAM policy for the bucket.

        .. note::

           Blob- / object-level IAM support does not yet exist and methods
           currently call an internal ACL backend not providing any utility
           beyond the blob's :attr:`acl` at this time. The API may be enhanced
           in the future and is currently undocumented. Use :attr:`acl` for
           managing object access control.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type policy: :class:`google.api_core.iam.Policy`
        :param policy: policy instance used to update bucket's IAM policy.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the current bucket.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :rtype: :class:`google.api_core.iam.Policy`
        :returns: the policy instance, based on the resource returned from
                  the ``setIamPolicy`` API request.
        Nrn   r`  
resourceIdra  )r   rk   rh   to_api_repr_put_resourcer   rb  )	rQ   policyrj   r   r   r   rh   r   r   rU   rU   rV   set_iam_policy  s    
)



zBlob.set_iam_policyc                 C   sR   |  |}d|i}| jdur| j|d< | j d}|j||||dd}|dg S )aN  API call:  test permissions

        .. note::

           Blob- / object-level IAM support does not yet exist and methods
           currently call an internal ACL backend not providing any utility
           beyond the blob's :attr:`acl` at this time. The API may be enhanced
           in the future and is currently undocumented. Use :attr:`acl` for
           managing object access control.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type permissions: list of string
        :param permissions: the permissions to check

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the current bucket.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :rtype: list of string
        :returns: the permissions returned by the ``testIamPermissions`` API
                  request.
        permissionsNrn   z/iam/testPermissionsra  )r   rk   rh   r   r   )rQ   rj  rj   r   r   r   rh   resprU   rU   rV   test_iam_permissionsU  s   
%

zBlob.test_iam_permissionsc              	   C   ,   | j    | j j|||||||d dS )a'  Update blob's ACL, granting read access to anonymous users.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: (Optional) The client to use.  If not passed, falls back
                       to the ``client`` stored on the blob's bucket.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`
        rj   r   r   r   r   r   r   N)rd   all
grant_readsaverQ   rj   r   r   r   r   r   r   rU   rU   rV   make_public     *
zBlob.make_publicc              	   C   rm  )a(  Update blob's ACL, revoking read access for anonymous users.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: (Optional) The client to use.  If not passed, falls back
                       to the ``client`` stored on the blob's bucket.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`
        rn  N)rd   ro  revoke_readrq  rr  rU   rU   rV   make_private  rt  zBlob.make_privatec                 C   s:  t |}| |}i }	t|tr$tjttdd |dur tt	|}d}t|tr3tjt
tdd d}|du r<dg| }t ||krFttg }
t||D ] \}}|j|jd}i }|durb||d< |rh||d< |
| qM|
| j d}| jdur| j|	d< t|	||d	 |j| j d
||	||| d}| | dS )a	  Concatenate source blobs into this one.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        See [API reference docs](https://cloud.google.com/storage/docs/json_api/v1/objects/compose)
        and a [code sample](https://cloud.google.com/storage/docs/samples/storage-compose-file#storage_compose_file-python).

        :type sources: list of :class:`Blob`
        :param sources: Blobs whose contents will be composed into this blob.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use. If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) Makes the operation conditional on whether the
            destination object's current generation matches the given value.
            Setting to 0 makes the operation succeed only if there are no live
            versions of the object.
            Note: In a previous version, this argument worked identically to the
            ``if_source_generation_match`` argument. For
            backwards-compatibility reasons, if a list is passed in,
            this argument will behave like ``if_source_generation_match``
            and also issue a DeprecationWarning.

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) Makes the operation conditional on whether the
            destination object's current metageneration matches the given
            value.

            If a list of long is passed in, no match operation will be
            performed.  (Deprecated: type(list of long) is supported for
            backwards-compatability reasons only.)

        :type if_source_generation_match: list of long
        :param if_source_generation_match:
            (Optional) Makes the operation conditional on whether the current
            generation of each source blob matches the corresponding generation.
            The list must match ``sources`` item-to-item.

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`
        r   r   N)rA   rI   r$  objectPreconditions)sourceObjectsdestinationrn   )r   r   z/composera  )r*  r   rA  listr  r  &_COMPOSE_IF_GENERATION_LIST_DEPRECATEDrG  r\   :_COMPOSE_IF_GENERATION_LIST_AND_IF_SOURCE_GENERATION_ERROR*_COMPOSE_IF_METAGENERATION_LIST_DEPRECATED,_COMPOSE_IF_SOURCE_GENERATION_MISMATCH_ERRORziprA   rI   r   rP   copyrk   r   _post_resourcerh   rJ  )rQ   sourcesrj   r   r   r   if_source_generation_matchr   sources_lenr   source_objectssourcesource_generationsource_objectpreconditionsrequestapi_responserU   rU   rV   compose  sl   ?






zBlob.composec                 C   s  |  |}t| j}|t|jdd | j}d|v r|d= |r$||d< |jr,|j|d< | jdur;d| jvr;| j|d< t|||||||	|
|d		 |j d
| j }|j	|| j
||||| d}t|d }t|d }|d rz| |d  d||fS |d ||fS )a  Rewrite source blob into this one.

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        .. note::

           ``rewrite`` is not supported in a ``Batch`` context.

        :type source: :class:`Blob`
        :param source: blob whose contents will be rewritten into this blob.

        :type token: str
        :param token:
            (Optional) Token returned from an earlier, not-completed call to
            rewrite the same source blob.  If passed, result will include
            updated status, total bytes written.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`
            Note that the generation to be matched is that of the
            ``destination`` blob.

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`
            Note that the generation to be matched is that of the
            ``destination`` blob.

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`
            Note that the metageneration to be matched is that of the
            ``destination`` blob.

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`
            Note that the metageneration to be matched is that of the
            ``destination`` blob.

        :type if_source_generation_match: long
        :param if_source_generation_match:
            (Optional) Makes the operation conditional on whether the source
            object's generation matches the given value.

        :type if_source_generation_not_match: long
        :param if_source_generation_not_match:
            (Optional) Makes the operation conditional on whether the source
            object's generation does not match the given value.

        :type if_source_metageneration_match: long
        :param if_source_metageneration_match:
            (Optional) Makes the operation conditional on whether the source
            object's current metageneration matches the given value.

        :type if_source_metageneration_not_match: long
        :param if_source_metageneration_not_match:
            (Optional) Makes the operation conditional on whether the source
            object's current metageneration does not match the given value.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`

        :rtype: tuple
        :returns: ``(token, bytes_rewritten, total_bytes)``, where ``token``
                  is a rewrite token (``None`` if the rewrite is complete),
                  ``bytes_rewritten`` is the number of bytes rewritten so far,
                  and ``total_bytes`` is the total number of bytes to be
                  rewritten.
        T)r  rI   rewriteTokensourceGenerationNr"  destinationKmsKeyName)r   r   r   r   r  if_source_generation_not_matchif_source_metageneration_match"if_source_metageneration_not_matchz
/rewriteTor   totalBytesRewritten
objectSizedoner   )r   rl   rO   r   rp   rI   rG   r   rh   r  rP   intrJ  )rQ   r  tokenrj   r   r   r   r   r  r  r  r  r   r   r   r   rh   r  	rewrittenr/  rU   rU   rV   rewritez  sP   
c




	
zBlob.rewritec                 C   sr   |  d| | j| |||||||	|
||d\}}}|dur7| j| ||||||||	|
||d\}}}|dusdS dS )a  Update blob's storage class via a rewrite-in-place. This helper will
        wait for the rewrite to complete before returning, so it may take some
        time for large files.

        See
        https://cloud.google.com/storage/docs/per-object-storage-class

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type new_class: str
        :param new_class:
            new storage class for the object.   One of:
            :attr:`~google.cloud.storage.constants.NEARLINE_STORAGE_CLASS`,
            :attr:`~google.cloud.storage.constants.COLDLINE_STORAGE_CLASS`,
            :attr:`~google.cloud.storage.constants.ARCHIVE_STORAGE_CLASS`,
            :attr:`~google.cloud.storage.constants.STANDARD_STORAGE_CLASS`,
            :attr:`~google.cloud.storage.constants.MULTI_REGIONAL_LEGACY_STORAGE_CLASS`,
            or
            :attr:`~google.cloud.storage.constants.REGIONAL_LEGACY_STORAGE_CLASS`.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use.  If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`
            Note that the generation to be matched is that of the
            ``destination`` blob.

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`
            Note that the generation to be matched is that of the
            ``destination`` blob.

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`
            Note that the metageneration to be matched is that of the
            ``destination`` blob.

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`
            Note that the metageneration to be matched is that of the
            ``destination`` blob.

        :type if_source_generation_match: long
        :param if_source_generation_match:
            (Optional) Makes the operation conditional on whether the source
            object's generation matches the given value.

        :type if_source_generation_not_match: long
        :param if_source_generation_not_match:
            (Optional) Makes the operation conditional on whether the source
            object's generation does not match the given value.

        :type if_source_metageneration_match: long
        :param if_source_metageneration_match:
            (Optional) Makes the operation conditional on whether the source
            object's current metageneration matches the given value.

        :type if_source_metageneration_not_match: long
        :param if_source_metageneration_not_match:
            (Optional) Makes the operation conditional on whether the source
            object's current metageneration does not match the given value.

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry:
            (Optional) How to retry the RPC. See: :ref:`configuring_retries`
        rC   )
r   r   r   r   r  r  r  r  r   r   N)r  r   r   r   r   r  r  r  r  r   r   )_patch_propertyr  )rQ   	new_classrj   r   r   r   r   r  r  r  r  r   r   r  r  rU   rU   rV   update_storage_class  s<   _zBlob.update_storage_classrc                 K   s   |dkr|s
|s
|rt d|rt dt| fd|i|S |dkr7|s(|s(|r,t dt| f||d|S |dv rQ|rAt dtt| fd|i||||dS |d	v rn|d
u r]t dtt| f|dd||||dS td)ay  Create a file handler for file-like I/O to or from this blob.

        This method can be used as a context manager, just like Python's
        built-in 'open()' function.

        While reading, as with other read methods, if blob.generation is not set
        the most recent blob generation will be used. Because the file-like IO
        reader downloads progressively in chunks, this could result in data from
        multiple versions being mixed together. If this is a concern, use
        either bucket.get_blob(), or blob.reload(), which will download the
        latest generation number and set it; or, if the generation is known, set
        it manually, for instance with bucket.blob(generation=123456).

        Checksumming (hashing) to verify data integrity is disabled for reads
        using this feature because reads are implemented using request ranges,
        which do not provide checksums to validate. See
        https://cloud.google.com/storage/docs/hashes-etags for details.

        See a [code sample](https://github.com/googleapis/python-storage/blob/main/samples/snippets/storage_fileio_write_read.py).

        Keyword arguments to pass to the underlying API calls.
        For both uploads and downloads, the following arguments are
        supported:

        - ``if_generation_match``
        - ``if_generation_not_match``
        - ``if_metageneration_match``
        - ``if_metageneration_not_match``
        - ``timeout``
        - ``retry``

        For downloads only, the following additional arguments are supported:

        - ``raw_download``

        For uploads only, the following additional arguments are supported:

        - ``content_type``
        - ``num_retries``
        - ``predefined_acl``
        - ``checksum``

        .. note::

           ``num_retries`` is supported for backwards-compatibility
           reasons only; please use ``retry`` with a Retry object or
           ConditionalRetryPolicy instead.

        :type mode: str
        :param mode:
            (Optional) A mode string, as per standard Python `open()` semantics.The first
            character must be 'r', to open the blob for reading, or 'w' to open
            it for writing. The second character, if present, must be 't' for
            (unicode) text mode, or 'b' for bytes mode. If the second character
            is omitted, text mode is the default.

        :type chunk_size: long
        :param chunk_size:
            (Optional) For reads, the minimum number of bytes to read at a time.
            If fewer bytes than the chunk_size are requested, the remainder is
            buffered. For writes, the maximum number of bytes to buffer before
            sending data to the server, and the size of each request when data
            is sent. Writes are implemented as a "resumable upload", so
            chunk_size for writes must be exactly a multiple of 256KiB as with
            other resumable uploads. The default is 40 MiB.

        :type ignore_flush: bool
        :param ignore_flush:
            (Optional) For non text-mode writes, makes flush() do nothing
            instead of raising an error. flush() without closing is not
            supported by the remote service and therefore calling it normally
            results in io.UnsupportedOperation. However, that behavior is
            incompatible with some consumers and wrappers of file objects in
            Python, such as zipfile.ZipFile or io.TextIOWrapper. Setting
            ignore_flush will cause flush() to successfully do nothing, for
            compatibility with those contexts. The correct way to actually flush
            data to the remote server is to close() (using a context manager,
            such as in the example, will cause this to happen automatically).

        :type encoding: str
        :param encoding:
            (Optional) For text mode only, the name of the encoding that the stream will
            be decoded or encoded with. If omitted, it defaults to
            locale.getpreferredencoding(False).

        :type errors: str
        :param errors:
            (Optional) For text mode only, an optional string that specifies how encoding
            and decoding errors are to be handled. Pass 'strict' to raise a
            ValueError exception if there is an encoding error (the default of
            None has the same effect), or pass 'ignore' to ignore errors. (Note
            that ignoring encoding errors can lead to data loss.) Other more
            rarely-used options are also available; see the Python 'io' module
            documentation for 'io.TextIOWrapper' for a complete list.

        :type newline: str
        :param newline:
            (Optional) For text mode only, controls how line endings are handled. It can
            be None, '', '\n', '\r', and '\r\n'. If None, reads use "universal
            newline mode" and writes use the system default. See the Python
            'io' module documentation for 'io.TextIOWrapper' for details.

        :returns: A 'BlobReader' or 'BlobWriter' from
            'google.cloud.storage.fileio', or an 'io.TextIOWrapper' around one
            of those classes, depending on the 'mode' argument.
        rQ  z=encoding, errors and newline arguments are for text mode onlyz5ignore_flush argument is for non-text write mode onlyrL   r   )rL   ignore_flush)r  rt)r  errorsnewline)wwtFzIignore_flush is required for text mode writing and cannot be set to FalseTzFSupported modes strings are 'r', 'rb', 'rt', 'w', 'wb', and 'wt' only.)r\   r4   r5   r   NotImplementedError)rQ   moderL   r  r  r  r  r   rU   rU   rV   r     s^   tz	Blob.openr9   r:   r;   r<   r=   c                 C   s   t |tr||
d}|j|d}| |}| j|||	|
|d}t| j}d|d< t|||d i t|j	j
|d||j}|j}z| j||||||||||d
 W d	S  tjyk } zt| W Y d	}~d	S d	}~ww )
a-  Download the contents of a blob object into a file-like object.

        See https://cloud.google.com/storage/docs/downloading-objects

        If :attr:`user_project` is set on the bucket, bills the API request
        to that project.

        :type file_obj: file
        :param file_obj: A file handle to which to write the blob's data.

        :type client: :class:`~google.cloud.storage.client.Client`
        :param client:
            (Optional) The client to use. If not passed, falls back to the
            ``client`` stored on the blob's bucket.

        :type start: int
        :param start: (Optional) The first byte in a range to be downloaded.

        :type end: int
        :param end: (Optional) The last byte in a range to be downloaded.

        :type raw_download: bool
        :param raw_download:
            (Optional) If true, download the object without any expansion.

        :type if_etag_match: Union[str, Set[str]]
        :param if_etag_match:
            (Optional) See :ref:`using-if-etag-match`

        :type if_etag_not_match: Union[str, Set[str]]
        :param if_etag_not_match:
            (Optional) See :ref:`using-if-etag-not-match`

        :type if_generation_match: long
        :param if_generation_match:
            (Optional) See :ref:`using-if-generation-match`

        :type if_generation_not_match: long
        :param if_generation_not_match:
            (Optional) See :ref:`using-if-generation-not-match`

        :type if_metageneration_match: long
        :param if_metageneration_match:
            (Optional) See :ref:`using-if-metageneration-match`

        :type if_metageneration_not_match: long
        :param if_metageneration_not_match:
            (Optional) See :ref:`using-if-metageneration-not-match`

        :type timeout: float or tuple
        :param timeout:
            (Optional) The amount of time, in seconds, to wait
            for the server response.  See: :ref:`configuring_timeouts`

        :type checksum: str
        :param checksum:
            (Optional) The type of checksum to compute to verify the integrity
            of the object. The response headers must contain a checksum of the
            requested type. If the headers lack an appropriate checksum (for
            instance in the case of transcoded or ranged downloads where the
            remote service does not know the correct checksum, including
            downloads where chunk_size is set) an INFO-level log will be
            emitted. Supported values are "md5", "crc32c" and None. The default
            is "md5".

        :type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
        :param retry: (Optional) How to retry the RPC. A None value will disable
            retries. A google.api_core.retry.Retry value will enable retries,
            and the object will define retriable response codes and errors and
            configure backoff and timeout options.

            A google.cloud.storage.retry.ConditionalRetryPolicy value wraps a
            Retry object and activates it only if certain conditions are met.
            This class exists to provide safe defaults for RPC calls that are
            not technically safe to retry normally (due to potential data
            duplication or other side-effects) but become safe to retry if a
            condition such as if_metageneration_match is set.

            See the retry.py source code and docstrings in this package
            (google.cloud.storage.retry) for information on retry types and how
            to configure them.

            Media operations (downloads and uploads) do not support non-default
            predicates in a Retry object. The default will always be used. Other
            configuration changes for Retry objects such as delays and deadlines
            are respected.

        :type command: str
        :param command:
            (Optional) Information about which interface for download was used,
            to be included in the X-Goog-API-Client header. Please leave as None
            unless otherwise directed.
        r>  r?  r   gzipzaccept-encodingr   r  )r   r   r   N)rA  r/   rB  r   r   rl   rO   r   r   r   r  r  r   r   r
   rK  rL  )rQ   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   rN  rU   rU   rV   r   u  sZ   
p

zBlob._prep_and_do_downloadc                 C       | j d}|durt|S dS )a  Number of underlying components that make up this object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: int or ``NoneType``
        :returns: The component count (in case of a composed object) or
                  ``None`` if the blob's resource has not been loaded from
                  the server.  This property will not be set on objects
                  not created via ``compose``.
        componentCountNrP   r   r  )rQ   component_countrU   rU   rV   r       zBlob.component_countc                 C      | j dS )a|  Retrieve the ETag for the object.

        See [`RFC 2616 (etags)`](https://tools.ietf.org/html/rfc2616#section-3.11) and
        [`API reference docs`](https://cloud.google.com/storage/docs/json_api/v1/objects).

        :rtype: str or ``NoneType``
        :returns: The blob etag or ``None`` if the blob's resource has not
                  been loaded from the server.
        r   rP   r   rX   rU   rU   rV   r   )  s   z	Blob.etageventBasedHoldc                 C   r  )a#  Retrieve the generation for the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: int or ``NoneType``
        :returns: The generation of the blob or ``None`` if the blob's
                  resource has not been loaded from the server.
        rI   Nr  )rQ   rI   rU   rU   rV   rI   @     
zBlob.generationc                 C   r  )ad  Retrieve the ID for the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        The ID consists of the bucket name, object name, and generation number.

        :rtype: str or ``NoneType``
        :returns: The ID of the blob or ``None`` if the blob's
                  resource has not been loaded from the server.
        idr  rX   rU   rU   rV   r  N  s   zBlob.idr?   c                 C   r  )a,  Retrieve the media download URI for the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: str or ``NoneType``
        :returns: The media link for the blob or ``None`` if the blob's
                  resource has not been loaded from the server.
        	mediaLinkr  rX   rU   rU   rV   r   j     
zBlob.media_linkc                 C      t | jdS )a  Retrieve arbitrary/application specific metadata for the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :setter: Update arbitrary/application specific metadata for the
                 object.
        :getter: Retrieve arbitrary/application specific metadata for
                 the object.

        :rtype: dict or ``NoneType``
        :returns: The metadata associated with the blob or ``None`` if the
                  property is not set.
        r@   r  deepcopyrP   r   rX   rU   rU   rV   r@   v  s   zBlob.metadatac                 C   s*   |durdd |  D }| d| dS )aM  Update arbitrary/application specific metadata for the object.

        Values are stored to GCS as strings. To delete a key, set its value to
        None and call blob.patch().

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :type value: dict
        :param value: The blob metadata to set.
        Nc                 S   s&   i | ]\}}||d urt |nd qS N)str).0kvrU   rU   rV   
<dictcomp>  s   & z!Blob.metadata.<locals>.<dictcomp>r@   )itemsr  r]   rU   rU   rV   r@     s   c                 C   r  )a+  Retrieve the metageneration for the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: int or ``NoneType``
        :returns: The metageneration of the blob or ``None`` if the blob's
                  resource has not been loaded from the server.
        r   Nr  )rQ   r   rU   rU   rV   r     r  zBlob.metagenerationc                 C   r  )a*  Retrieve info about the owner of the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: dict or ``NoneType``
        :returns: Mapping of owner's role/ID, or ``None`` if the blob's
                  resource has not been loaded from the server.
        ownerr  rX   rU   rU   rV   r    s   
z
Blob.ownerc                 C   r  )aW  Retrieve timestamp at which the object's retention period expires.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns: Datetime object parsed from RFC3339 valid timestamp, or
                  ``None`` if the property is not set locally.
        retentionExpirationTimeNrP   r   r   r]   rU   rU   rV   retention_expiration_time  r  zBlob.retention_expiration_timec                 C   r  )a  Retrieve the URI for the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: str or ``NoneType``
        :returns: The self link for the blob or ``None`` if the blob's
                  resource has not been loaded from the server.
        selfLinkr  rX   rU   rU   rV   	self_link  r  zBlob.self_linkc                 C   r  )a  Size of the object, in bytes.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: int or ``NoneType``
        :returns: The size of the blob or ``None`` if the blob's
                  resource has not been loaded from the server.
        r/  Nr  )rQ   r/  rU   rU   rV   r/    r  z	Blob.sizec                 C   r  )a  Resource name of Cloud KMS key used to encrypt the blob's contents.

        :rtype: str or ``NoneType``
        :returns:
            The resource name or ``None`` if no Cloud KMS key was used,
            or the blob's resource has not been loaded from the server.
        rH   r  rX   rU   rU   rV   rG     s   	zBlob.kms_key_namec                 C   s   |  d| dS )zSet KMS encryption key for object.

        :type value: str or ``NoneType``
        :param value: new KMS key name (None to clear any existing key).
        rH   N)r  r]   rU   rU   rV   rG     s   rC   temporaryHoldc                 C   r  )a  Retrieve the timestamp at which the object was deleted.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns: Datetime object parsed from RFC3339 valid timestamp, or
                  ``None`` if the blob's resource has not been loaded from
                  the server (see :meth:`reload`). If the blob has
                  not been deleted, this will never be set.
        timeDeletedNr  r]   rU   rU   rV   time_deleted  r  zBlob.time_deletedc                 C   r  )a  Retrieve the timestamp at which the object was created.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns: Datetime object parsed from RFC3339 valid timestamp, or
                  ``None`` if the blob's resource has not been loaded from
                  the server (see :meth:`reload`).
        timeCreatedNr  r]   rU   rU   rV   time_created     zBlob.time_createdc                 C   r  )a  Retrieve the timestamp at which the object was updated.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns: Datetime object parsed from RFC3339 valid timestamp, or
                  ``None`` if the blob's resource has not been loaded from
                  the server (see :meth:`reload`).
        r   Nr  r]   rU   rU   rV   r   -  r  zBlob.updatedc                 C   r  )a|  Retrieve the custom time for the object.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns: Datetime object parsed from RFC3339 valid timestamp, or
                  ``None`` if the blob's resource has not been loaded from
                  the server (see :meth:`reload`).
        r>   Nr  r]   rU   rU   rV   custom_time<  r  zBlob.custom_timec                 C   s    |durt |}| d| dS )a  Set the custom time for the object.

        Once set on the server side object, this value can't be unset, but may
        only changed to a custom datetime in the future.

        If :attr:`custom_time` must be unset, either perform a rewrite
        operation or upload the data again.

        See https://cloud.google.com/storage/docs/json_api/v1/objects

        :type value: :class:`datetime.datetime`
        :param value: new value
        Nr>   )r   r  r]   rU   rU   rV   r  K  s   c                 C   s   | j di }t|| S )zRetrieve the retention configuration for this object.

        :rtype: :class:`Retention`
        :returns: an instance for managing the object's retention configuration.
        rB   )rP   r   	Retentionrb  )rQ   r   rU   rU   rV   rB   _  s   zBlob.retentionc                 C   r  )a9  If this object has been soft-deleted, returns the time at which it became soft-deleted.

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns:
            (readonly) The time that the object became soft-deleted.
             Note this property is only set for soft-deleted objects.
        softDeleteTimeNr  )rQ   soft_delete_timerU   rU   rV   r  i     	zBlob.soft_delete_timec                 C   r  )aH  If this object has been soft-deleted, returns the time at which it will be permanently deleted.

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns:
            (readonly) The time that the object will be permanently deleted.
            Note this property is only set for soft-deleted objects.
        hardDeleteTimeNr  )rQ   hard_delete_timerU   rU   rV   r  v  r  zBlob.hard_delete_time)NNNNr  )NNr   NNNNNNNNNNNNFNr   )NN)r  NNNNN)h__name__
__module____qualname____doc__rZ   r[   r.   r,   r*   r)   r+   r-   STORAGE_CLASSESrK   propertyrR   rL   setterrF   staticmethodrc   rd   rg   rh   rj   rk   rm   rp   ry   classmethodr   r   r(   r0   r   r2   r   r   r   r   r   r   r   r   r   r  r  r  r  r   r4  r;  r=  rE  rO  rP  rU  rV  rX  r^  rd  r1   ri  rl  r3   rs  rv  r  r  r  r   r   cache_controlcontent_dispositioncontent_encodingcontent_languager   r   r=   r   r  r   event_based_holdrI   r  md5_hashr   r@   r   r  r  r  r/  rG   storage_classtemporary_holdr  r  r   r  rB   r  r  __classcell__rU   rU   rS   rV   rD      sT   "










	
	
 
 a
k
=
;0
x
 

~
r

y
!1
 8
 W
 
 4
 6
 

 
 
 6
G
>
8
7
8
 	
 "
 
 #	
 %

	












	





	
rD   c                 C   s   t | ds| jS |  S )zReturns the host name from the given connection.

    :type connection: :class:`~google.cloud.storage._http.Connection`
    :param connection: The connection object.

    :rtype: str
    :returns: The host name.
    get_api_base_url_for_mtls)hasattrAPI_BASE_URLr  )
connectionrU   rU   rV   r     s
   r   Fc                 C   sh   | du ri S t | } t|  }t|}t| } |r d}nd}|d d|d t| |d t|iS )ak  Builds customer encryption key headers

    :type key: bytes
    :param key: 32 byte key to build request key and hash.

    :type source: bool
    :param source: If true, return headers for the "source" blob; otherwise,
                   return headers for the "destination" blob.

    :rtype: dict
    :returns: dict of HTTP headers being sent in request.
    NzX-Goog-Copy-Source-Encryption-zX-Goog-Encryption-	AlgorithmAES256Keyz
Key-Sha256)r   hashlibsha256r   base64	b64encoder   )r  r  key_hashprefixrU   rU   rV   rl     s   

rl      ~c                 C   s   t | dd} t| |dS )a  URL-quote a string.

    If the value is unicode, this method first UTF-8 encodes it as bytes and
    then quotes the bytes. (In Python 3, ``urllib.parse.quote`` does this
    encoding automatically, but in Python 2, non-ASCII characters cannot be
    quoted.)

    :type value: str or bytes
    :param value: The value to be URL-quoted.

    :type safe: bytes
    :param safe: Bytes *not* to be quoted.  By default, includes only ``b'~'``.

    :rtype: str
    :returns: The encoded value (bytes in Python 2, unicode in Python 3).
    r	  rW  rr   )r   r   )r^   rs   rU   rU   rV   r`     s   r`   c                 C   s   |r|  dtj dS dS )zRewind the stream if desired.

    :type stream: IO[bytes]
    :param stream: A bytes IO object open for reading.

    :type rewind: bool
    :param rewind: Indicates if we should seek to the beginning of the stream.
    r   N)seekr   SEEK_SET)r   rF  rU   rU   rV   rH    s   	rH  c                 C   sV   | j }|jr|jd t|  }nt| }|jj d|jj d| }tj|j||d)aR  Re-wrap and raise an ``InvalidResponse`` exception.

    :type error: :exc:`google.resumable_media.InvalidResponse`
    :param error: A caught exception from the ``google-resumable-media``
                  library.

    :raises: :class:`~google.cloud.exceptions.GoogleCloudError` corresponding
             to the failed status code
    z:  )r   )	r   textr  r  r   urlr   from_http_statusstatus_code)errorr   error_messagemessagerU   rU   rV   rL    s   
rL  c                 C   sJ   t |dkr| S t| \}}}}}t|}|| t|||t||fS )ae  Add one query parameter to a base URL.

    :type base_url: string
    :param base_url: Base URL (may already contain query parameters)

    :type name_value_pairs: list of (string, string) tuples.
    :param name_value_pairs: Names and values of the query parameters to add

    :rtype: string
    :returns: URL with additional query strings appended.
    r   )r*  r   r   extendr	   r   )r   r   r   netlocrh   queryfragrU   rU   rV   r     s   
r   c                       s   e Zd ZdZ			d fdd	Zedd Zedd Zed	d
 Z	e	j
dd
 Z	edd Zej
dd Zedd Z  ZS )r  a  Map an object's retention configuration.

    :type blob: :class:`Blob`
    :params blob: blob for which this retention configuration applies to.

    :type mode: str or ``NoneType``
    :params mode:
        (Optional) The mode of the retention configuration, which can be either Unlocked or Locked.
        See: https://cloud.google.com/storage/docs/object-lock

    :type retain_until_time: :class:`datetime.datetime` or ``NoneType``
    :params retain_until_time:
        (Optional) The earliest time that the object can be deleted or replaced, which is the
        retention configuration set for this object.

    :type retention_expiration_time: :class:`datetime.datetime` or ``NoneType``
    :params retention_expiration_time:
        (Optional) The earliest time that the object can be deleted, which depends on any
        retention configuration set for the object and any retention policy set for the bucket
        that contains the object. This value should normally only be set by the back-end API.
    Nc                    sR   d|i}|d urt |}||d< |d urt |}||d< tt| | || _d S )Nr  retainUntilTimer  )r   rJ   r  rK   _blob)rQ   blobr  retain_until_timer  r  rS   rU   rV   rK     s   
zRetention.__init__c                 C   s   | |}| | |S )ad  Factory:  construct instance from resource.

        :type blob: :class:`Blob`
        :params blob: Blob for which this retention configuration applies to.

        :type resource: dict
        :param resource: mapping as returned from API call.

        :rtype: :class:`Retention`
        :returns: Retention configuration created from resource.
        )r   )r   r   r   instancerU   rU   rV   rb  1  s   
zRetention.from_api_reprc                 C   rW   )zBlob for which this retention configuration applies to.

        :rtype: :class:`Blob`
        :returns: the instance's blob.
        )r  rX   rU   rU   rV   r   B  rY   zRetention.blobc                 C   s
   |  dS )zThe mode of the retention configuration. Options are 'Unlocked' or 'Locked'.

        :rtype: string
        :returns: The mode of the retention configuration, which can be either set to 'Unlocked' or 'Locked'.
        r  )r   rX   rU   rU   rV   r  K  s   
zRetention.modec                 C   s   || d< | j d|  d S )Nr  rB   )r   r  r]   rU   rU   rV   r  T  s   c                 C      |  d}|durt|S dS )a  The earliest time that the object can be deleted or replaced, which is the
        retention configuration set for this object.

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns: Datetime object parsed from RFC3339 valid timestamp, or
                  ``None`` if the blob's resource has not been loaded from
                  the server (see :meth:`reload`).
        r  Nr   r   r]   rU   rU   rV   r  Y     

zRetention.retain_until_timec                 C   s*   |durt |}|| d< | jd|  dS )zSet the retain_until_time for the object retention configuration.

        :type value: :class:`datetime.datetime`
        :param value: The earliest time that the object can be deleted or replaced.
        Nr  rB   )r   r   r  r]   rU   rU   rV   r  g  s   c                 C   r  )ag  The earliest time that the object can be deleted, which depends on any
        retention configuration set for the object and any retention policy set for
        the bucket that contains the object.

        :rtype: :class:`datetime.datetime` or ``NoneType``
        :returns:
            (readonly) The earliest time that the object can be deleted.
        r  Nr  )rQ   r  rU   rU   rV   r  s  r  z#Retention.retention_expiration_time)NNN)r  r  r  r  rK   r  rb  r  r   r  r  r  r  r  rU   rU   rS   rV   r    s(    





r  )F)r  )jr  r  r  r  ior   r   loggingr  r   r   email.parserr   urllib.parser   r   r   r   r	   r  googler
   google.resumable_media.requestsr   r   r   r   r   r   google.api_core.iamr   google.cloudr   google.cloud._helpersr   r   r   r   google.cloud.exceptionsr   google.cloud.storage._helpersr   r   r   r   r   r   r   r   r    google.cloud.storage._signingr!   r"   r#   r$   r%   google.cloud.storage.aclr&   r'   google.cloud.storage.constantsr(   r)   r*   r+   r,   r-   r.   google.cloud.storage.retryr/   r0   r1   r2   r3   google.cloud.storage.fileior4   r5   r  r   _BASE_UPLOAD_TEMPLATEr-  r8  r   r  r+  r   r{  r|  r}  r~  r  compiler}   r7  rC  	getLoggerr  r   rD   r   rl   r`   rH  rL  r   r  r  rU   rU   rU   rV   <module>   s"  
                                    

!
