o
    Vh!Q                     @   s   d Z ddlZddlZddlZddlmZ ddlZddlmZ G dd de	Z
G dd	 d	eZd
d ZG dd deZdd Zdd Zdd Zejdd Zdd Zdd ZG dd deZG dd dejZG dd deZG d d! d!eZdS )"z

requests_toolbelt.multipart.encoder
===================================

This holds all of the implementation details of the MultipartEncoder

    N)uuid4   fieldsc                   @   s   e Zd ZdZdS )FileNotSupportedErrorzFile not supported error.N)__name__
__module____qualname____doc__ r   r   w/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/requests_toolbelt/multipart/encoder.pyr      s    r   c                   @   s   e Zd ZdZd%ddZedd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zedd Zd d! Zd&d#d$ZdS )'MultipartEncodera  

    The ``MultipartEncoder`` object is a generic interface to the engine that
    will create a ``multipart/form-data`` body for you.

    The basic usage is:

    .. code-block:: python

        import requests
        from requests_toolbelt import MultipartEncoder

        encoder = MultipartEncoder({'field': 'value',
                                    'other_field': 'other_value'})
        r = requests.post('https://httpbin.org/post', data=encoder,
                          headers={'Content-Type': encoder.content_type})

    If you do not need to take advantage of streaming the post body, you can
    also do:

    .. code-block:: python

        r = requests.post('https://httpbin.org/post',
                          data=encoder.to_string(),
                          headers={'Content-Type': encoder.content_type})

    If you want the encoder to use a specific order, you can use an
    OrderedDict or more simply, a list of tuples:

    .. code-block:: python

        encoder = MultipartEncoder([('field', 'value'),
                                    ('other_field', 'other_value')])

    .. versionchanged:: 0.4.0

    You can also provide tuples as part values as you would provide them to
    requests' ``files`` parameter.

    .. code-block:: python

        encoder = MultipartEncoder({
            'field': ('file_name', b'{"a": "b"}', 'application/json',
                      {'X-My-Header': 'my-value'})
        ])

    .. warning::

        This object will end up directly in :mod:`httplib`. Currently,
        :mod:`httplib` has a hard-coded read size of **8192 bytes**. This
        means that it will loop until the file has been read and your upload
        could take a while. This is **not** a bug in requests. A feature is
        being considered for this object to allow you, the user, to specify
        what size should be returned on a read. If you have opinions on this,
        please weigh in on `this issue`_.

    .. _this issue:
        https://github.com/requests/toolbelt/issues/75

    Nutf-8c                 C   s   |pt  j| _d| j| _|| _dt| j| jtd| jg| _|| _	d| _
g | _tg | _d | _d | _t|d| _|   |   d S )Nz--{}    z
F)encoding)r   hexboundary_valueformatboundaryr   joinencode_with_encoded_boundaryr   finishedpartsiter_iter_parts_current_part_lenCustomBytesIO_buffer_prepare_parts_write_boundary)selfr   r   r   r   r   r   __init__W   s    

zMultipartEncoder.__init__c                 C   s   | j p|  S )ai  Length of the multipart/form-data body.

        requests will first attempt to get the length of the body by calling
        ``len(body)`` and then by checking for the ``len`` attribute.

        On 32-bit systems, the ``__len__`` method cannot return anything
        larger than an integer (in C) can hold. If the total size of the body
        is even slightly larger than 4GB users will see an OverflowError. This
        manifested itself in `bug #80`_.

        As such, we now calculate the length lazily as a property.

        .. _bug #80:
            https://github.com/requests/toolbelt/issues/80
        )r   _calculate_lengthr"   r   r   r   len   s   zMultipartEncoder.lenc                 C   s   d | jS )Nz<MultipartEncoder: {!r}>)r   r   r%   r   r   r   __repr__      zMultipartEncoder.__repr__c                    s2   t | j t fdd| jD   d | _| jS )z
        This uses the parts to calculate the length of the body.

        This returns the calculated length so __len__ can be lazy.
        c                 3   s     | ]} t | d  V  qdS )   N)	total_len).0pboundary_lenr   r   	<genexpr>   s    
z5MultipartEncoder._calculate_length.<locals>.<genexpr>r)   )r&   r   sumr   r   r%   r   r-   r   r$      s   
z"MultipartEncoder._calculate_lengthc                 C   s   |t | j }|dkr|S dS )a  This calculates how many bytes need to be added to the buffer.

        When a consumer read's ``x`` from the buffer, there are two cases to
        satisfy:

            1. Enough data in the buffer to return the requested amount
            2. Not enough data

        This function uses the amount of unread bytes in the buffer and
        determines how much the Encoder has to load before it can return the
        requested amount of bytes.

        :param int read_size: the number of bytes the consumer requests
        :returns: int -- the number of bytes that must be loaded into the
            buffer before the read can be satisfied. This will be strictly
            non-negative
        r   )r*   r   )r"   	read_sizeamountr   r   r   _calculate_load_amount   s   z'MultipartEncoder._calculate_load_amountc                 C   s   | j   | jp|  }|dks|dkrUd}|r-| s-|| d7 }||  7 }|  }|s:||  7 }d| _dS ||	| j |7 }|dkrK||8 }|dks|dksdS dS )z0Load ``amount`` number of bytes into the buffer.r   s   
TN)
r   smart_truncater   
_next_partbytes_left_to_write_writer!   _write_closing_boundaryr   write_to)r"   r2   partwrittenr   r   r   _load   s    
zMultipartEncoder._loadc                 C   s0   zt | j }| _W |S  ty   d }Y |S w N)nextr   r   StopIteration)r"   r,   r   r   r   r6      s   zMultipartEncoder._next_partc           	      c   s    | j }t| j drt| j  }|D ]C\}}d }d }d }t|ttfrBt|dkr/|\}}nt|dkr;|\}}}n	|\}}}}n|}t j||||d}|j|d |V  qd S )Nitemsr      )namedatafilenameheaders)content_type)	r   hasattrlistrA   
isinstancetupler&   RequestFieldmake_multipart)	r"   _fieldskv	file_name	file_typefile_headersfile_pointerfieldr   r   r   _iter_fields   s,   
zMultipartEncoder._iter_fieldsc                    s.   | j   fdd|  D | _t| j| _dS )zThis uses the fields provided by the user and creates Part objects.

        It populates the `parts` attribute and uses that to create a
        generator for iteration.
        c                    s   g | ]}t | qS r   )Part
from_field)r+   fencr   r   
<listcomp>   s    z3MultipartEncoder._prepare_parts.<locals>.<listcomp>N)r   rV   r   r   r   r%   r   rZ   r   r       s   zMultipartEncoder._prepare_partsc                 C      | j |S )zWrite the bytes to the end of the buffer.

        :param bytes bytes_to_write: byte-string (or bytearray) to append to
            the buffer
        :returns: int -- the number of bytes written
        )r   append)r"   bytes_to_writer   r   r   r8      s   zMultipartEncoder._writec                 C   s   |  | jS )z,Write the boundary to the end of the buffer.)r8   r   r%   r   r   r   r!     s   z MultipartEncoder._write_boundaryc                 C   sJ   t | j | jdd | jd W d   dS 1 sw   Y  dS )z?Write the bytes necessary to finish a multipart/form-data body.r   s   --
N)resetr   seekwriter%   r   r   r   r9     s   
z(MultipartEncoder._write_closing_boundaryc                 C   s   |  t|| jS )z/Write the current part's headers to the buffer.)r8   r   r   )r"   rF   r   r   r   _write_headers  s   zMultipartEncoder._write_headersc                 C   s   t d| jS )Nz multipart/form-data; boundary={})strr   r   r%   r   r   r   rG     s   
zMultipartEncoder.content_typec                 C      |   S )a  Return the entirety of the data in the encoder.

        .. note::

            This simply reads all of the data it can. If you have started
            streaming or reading data from the encoder, this method will only
            return whatever data is left in the encoder.

        .. note::

            This method affects the internal state of the encoder. Calling
            this method will exhaust the encoder.

        :returns: the multipart message
        :rtype: bytes
        readr%   r   r   r   	to_string  s   zMultipartEncoder.to_stringr4   c                 C   sJ   | j r	| j|S |}|dkr|dur| t|}| | | j|S )zRead data from the streaming encoder.

        :param int size: (optional), If provided, ``read`` will return exactly
            that many bytes. If it is not provided, it will return the
            remaining bytes.
        :returns: bytes
        r4   N)r   r   rh   r3   intr=   )r"   sizebytes_to_loadr   r   r   rh   +  s   
zMultipartEncoder.readNr   r4   )r   r   r	   r
   r#   propertyr&   r'   r$   r3   r=   r6   rV   r    r8   r!   r9   rd   rG   ri   rh   r   r   r   r   r      s(    
=+

	
r   c                 C   s   | S r>   r   )monitorr   r   r   IDENTITY>  s   rq   c                   @   sJ   e Zd ZdZdddZe		dddZedd	 Zd
d Z	dddZ
dS )MultipartEncoderMonitora  
    An object used to monitor the progress of a :class:`MultipartEncoder`.

    The :class:`MultipartEncoder` should only be responsible for preparing and
    streaming the data. For anyone who wishes to monitor it, they shouldn't be
    using that instance to manage that as well. Using this class, they can
    monitor an encoder and register a callback. The callback receives the
    instance of the monitor.

    To use this monitor, you construct your :class:`MultipartEncoder` as you
    normally would.

    .. code-block:: python

        from requests_toolbelt import (MultipartEncoder,
                                       MultipartEncoderMonitor)
        import requests

        def callback(monitor):
            # Do something with this information
            pass

        m = MultipartEncoder(fields={'field0': 'value0'})
        monitor = MultipartEncoderMonitor(m, callback)
        headers = {'Content-Type': monitor.content_type}
        r = requests.post('https://httpbin.org/post', data=monitor,
                          headers=headers)

    Alternatively, if your use case is very simple, you can use the following
    pattern.

    .. code-block:: python

        from requests_toolbelt import MultipartEncoderMonitor
        import requests

        def callback(monitor):
            # Do something with this information
            pass

        monitor = MultipartEncoderMonitor.from_fields(
            fields={'field0': 'value0'}, callback
            )
        headers = {'Content-Type': montior.content_type}
        r = requests.post('https://httpbin.org/post', data=monitor,
                          headers=headers)

    Nc                 C   s$   || _ |pt| _d| _| j j| _d S Nr   )encoderrq   callback
bytes_readr&   )r"   rt   ru   r   r   r   r#   u  s   
z MultipartEncoderMonitor.__init__r   c                 C   s   t |||}| ||S r>   )r   )clsr   r   r   ru   rt   r   r   r   from_fields  s   
z#MultipartEncoderMonitor.from_fieldsc                 C   s   | j jS r>   )rt   rG   r%   r   r   r   rG     s   z$MultipartEncoderMonitor.content_typec                 C   rf   r>   rg   r%   r   r   r   ri     s   z!MultipartEncoderMonitor.to_stringr4   c                 C   s,   | j |}|  jt|7  _| |  |S r>   )rt   rh   rv   r&   ru   )r"   rk   stringr   r   r   rh     s   
zMultipartEncoderMonitor.readr>   )Nr   Nrn   )r   r   r	   r
   r#   classmethodrx   ro   rG   ri   rh   r   r   r   r   rr   B  s    
1
rr   c                 C   s    | du st | ts| |S | S )a6  Encoding ``string`` with ``encoding`` if necessary.

    :param str string: If string is a bytes object, it will not encode it.
        Otherwise, this function will encode it with the provided encoding.
    :param str encoding: The encoding with which to encode string.
    :returns: encoded bytes object
    N)rJ   bytesencode)ry   r   r   r   r   r     s   
r   c                 C   s   t | dr| S t| |S )z4Coerce the data to an object with a ``read`` method.rh   )rH   r   rD   r   r   r   r   readable_data  s   

r~   c                 C   st   t | dr	t| S t | dr| jS t | dr-z|  }W n
 tjy&   Y nw t|jS t | dr8t|  S d S )N__len__r&   filenogetvalue)	rH   r&   r   ioUnsupportedOperationosfstatst_sizer   )or   r   r   r   r*     s   



r*   c                 c   s,    |   }| dd dV  | |d dS )a  Keep track of the buffer's current position and write to the end.

    This is a context manager meant to be used when adding data to the buffer.
    It eliminates the need for every function to be concerned with the
    position of the cursor in the buffer.
    r   r   Ntellrb   )bufferoriginal_positionr   r   r   ra     s
   ra   c                 C   sL   t | ts$t| drt|  |S t| drt| S t| ds$t| |S | S )z5Ensure that every object's __len__ behaves uniformly.r   r   rh   )rJ   r   rH   r   FileWrapperr}   r   r   r   coerce_data  s   




r   c                 C   s   t | drt|  S t| S )NrA   )rH   rI   rA   r   r   r   r   to_list  s   
r   c                   @   s0   e Zd Zdd Zedd Zdd Zdd Zd	S )
rW   c                 C   s,   || _ || _d| _t| j t| j | _d S )NT)rF   bodyheaders_unreadr&   r*   )r"   rF   r   r   r   r   r#     s   zPart.__init__c                 C   s$   t | |}t|j|}| ||S )z8Create a part from a Request Field generated by urllib3.)r   render_headersr   rD   )rw   rU   r   rF   r   r   r   r   rX     s   
zPart.from_fieldc                 C   s*   d}| j r|t| j7 }|t| j dkS )zDetermine if there are bytes left to write.

        :returns: bool -- ``True`` if there are bytes left to write, otherwise
            ``False``
        r   )r   r&   rF   r*   r   )r"   to_readr   r   r   r7     s   zPart.bytes_left_to_writec                 C   s   d}| j r||| j7 }d| _ t| jdkrC|dks||k rC|}|dkr)|| }||| j|7 }t| jdkrC|dks||k s|S )a  Write the requested amount of bytes to the buffer provided.

        The number of bytes written may exceed size on the first read since we
        load the headers ambitiously.

        :param CustomBytesIO buffer: buffer we want to write bytes to
        :param int size: number of bytes requested to be written to the buffer
        :returns: int -- number of bytes actually written
        r   Fr4   )r   r^   rF   r*   r   rh   )r"   r   rk   r<   amount_to_readr   r   r   r:     s   
zPart.write_toN)r   r   r	   r#   rz   rX   r7   r:   r   r   r   r   rW     s    
rW   c                       sB   e Zd Zd fdd	Zdd Zedd Zd	d
 Zdd Z  Z	S )r   Nr   c                    s   t ||}tt| | d S r>   )r   superr   r#   )r"   r   r   	__class__r   r   r#     s   
zCustomBytesIO.__init__c                 C   s,   |   }| dd |   }| |d |S )Nr   r   r   )r"   current_poslengthr   r   r   _get_end  s
   zCustomBytesIO._get_endc                 C   s   |   }||   S r>   )r   r   r"   r   r   r   r   r&   !  s   zCustomBytesIO.lenc                 C   s8   t |  | |}W d    |S 1 sw   Y  |S r>   )ra   rc   )r"   r{   r<   r   r   r   r^   &  s   

zCustomBytesIO.appendc                 C   sV   t | }|  | }||kr)|  }| dd |   | | | dd d S d S rs   )r*   r   rh   rb   truncaterc   )r"   
to_be_readalready_read	old_bytesr   r   r   r5   +  s   
zCustomBytesIO.smart_truncaterm   )
r   r   r	   r#   r   ro   r&   r^   r5   __classcell__r   r   r   r   r     s    
r   c                   @   s*   e Zd Zdd Zedd Zd	ddZdS )
r   c                 C   s
   || _ d S r>   )fd)r"   file_objectr   r   r   r#   8  s   
zFileWrapper.__init__c                 C   s   t | j| j  S r>   )r*   r   r   r%   r   r   r   r&   ;  s   zFileWrapper.lenr4   c                 C   r]   r>   )r   rh   r   r   r   r   rh   ?  r(   zFileWrapper.readNrn   )r   r   r	   r#   ro   r&   rh   r   r   r   r   r   7  s
    
r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
FileFromURLWrappera  File from URL wrapper.

    The :class:`FileFromURLWrapper` object gives you the ability to stream file
    from provided URL in chunks by :class:`MultipartEncoder`.
    Provide a stateless solution for streaming file from one server to another.
    You can use the :class:`FileFromURLWrapper` without a session or with
    a session as demonstated by the examples below:

    .. code-block:: python
        # no session

        import requests
        from requests_toolbelt import MultipartEncoder, FileFromURLWrapper

        url = 'https://httpbin.org/image/png'
        streaming_encoder = MultipartEncoder(
            fields={
                'file': FileFromURLWrapper(url)
            }
        )
        r = requests.post(
            'https://httpbin.org/post', data=streaming_encoder,
            headers={'Content-Type': streaming_encoder.content_type}
        )

    .. code-block:: python
        # using a session

        import requests
        from requests_toolbelt import MultipartEncoder, FileFromURLWrapper

        session = requests.Session()
        url = 'https://httpbin.org/image/png'
        streaming_encoder = MultipartEncoder(
            fields={
                'file': FileFromURLWrapper(url, session=session)
            }
        )
        r = session.post(
            'https://httpbin.org/post', data=streaming_encoder,
            headers={'Content-Type': streaming_encoder.content_type}
        )

    Nc                 C   s4   |pt  | _| |}t|jd | _|j| _d S )Ncontent-length)	requestsSessionsession_request_for_filerj   rF   r&   rawraw_data)r"   file_urlr   requested_filer   r   r   r#   q  s   
zFileFromURLWrapper.__init__c                 C   sZ   | j j|dd}|jdd}|du rdj|d}t|| s+dj|d}t||S )z&Make call for file under provided URL.T)streamr   NzhData from provided URL {url} is not supported. Lack of content-length Header in requested file response.)urlzZData from provided URL {url} is not supported. content-length header value is not a digit.)r   getrF   r   r   isdigit)r"   r   responsecontent_length	error_msgr   r   r   r   w  s    z$FileFromURLWrapper._request_for_filec                 C   s@   |dkr|n| j }| j|pd}|  j |rt |nd8  _ |S )zRead file in chunks.r   r   )r&   r   rh   )r"   
chunk_sizechunkr   r   r   rh     s   zFileFromURLWrapper.readr>   )r   r   r	   r
   r#   r   rh   r   r   r   r   r   C  s
    
-r   )r
   
contextlibr   r   uuidr   r   _compatr   	Exceptionr   objectr   rq   rr   r   r~   r*   contextmanagerra   r   r   rW   BytesIOr   r   r   r   r   r   r   <module>   s0     (U
2"