
    $h!Q                     6   S r SSKrSSKrSSKrSSKJr  SSKrSSKJr   " S S\	5      r
 " S S	\5      rS
 r " S S\5      rS rS rS r\R$                  S 5       rS rS r " S S\5      r " S S\R.                  5      r " S S\5      r " S S\5      rg)z

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

This holds all of the implementation details of the MultipartEncoder

    N)uuid4   fieldsc                       \ rS rSrSrSrg)FileNotSupportedError   zFile not supported error. N)__name__
__module____qualname____firstlineno____doc____static_attributes__r
       [/var/www/html/shao/venv/lib/python3.13/site-packages/requests_toolbelt/multipart/encoder.pyr   r      s    #r   r   c                       \ rS rSrSrSS jr\S 5       rS rS r	S r
S	 rS
 rS rS rS rS rS rS r\S 5       rS rSS jrSrg)MultipartEncoder   aY  

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

Nc                    U=(       d    [        5       R                  U l        SR                  U R                  5      U l        X0l        SR                  [        U R                  U R
                  5      [        SU R
                  5      /5      U l        Xl	        SU l
        / U l        [        / 5      U l        S U l        S U l        [!        US9U l        U R%                  5         U R'                  5         g )Nz--{}r   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   s       r   __init__MultipartEncoder.__init__W   s    &5%'++ d&9&9: ! "%t}}5.+ "   
  8 " 	 %h7 	 	r   c                 H    U R                   =(       d    U R                  5       $ )a  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)   s    r   lenMultipartEncoder.len   s    $ yy4D2244r   c                 8    SR                  U R                  5      $ )Nz<MultipartEncoder: {!r}>)r   r   r.   s    r   __repr__MultipartEncoder.__repr__   s    )00==r   c                    ^ [        U R                  5      m[        U4S jU R                   5       5      T-   S-   U l        U R                  $ )zv
This uses the parts to calculate the length of the body.

This returns the calculated length so __len__ can be lazy.
c              3   D   >#    U H  nT[        U5      -   S -   v   M     g7f)   N)	total_len).0pboundary_lens     r   	<genexpr>5MultipartEncoder._calculate_length.<locals>.<genexpr>   s"      7A!\IaL(1,zs    r6   )r/   r   sumr    r$   )r)   r:   s    @r   r-   "MultipartEncoder._calculate_length   sL     4==) 7;zz  !	 yyr   c                 F    U[        U R                  5      -
  nUS:  a  U$ 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   )r7   r&   )r)   	read_sizeamounts      r   _calculate_load_amount'MultipartEncoder._calculate_load_amount   s(    $ Yt||44!v**r   c                    U R                   R                  5         U R                  =(       d    U R                  5       nUS:X  d  US:  a  SnU(       aJ  UR	                  5       (       d5  X0R                  S5      -  nX0R                  5       -  nU R                  5       nU(       d  X0R                  5       -  nSU l        gX2R                  U R                   U5      -  nUS:w  a  X-  nUS:X  a  M  US:  a  M  gg)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)   rA   partwrittens       r   _loadMultipartEncoder._load   s    ##%!!6T__%6lfqjGD4466;;w////11(7799 $}}T\\6::G|! lfqjr   c                 d     [        U R                  5      =ol        U$ ! [         a    S n U$ f = fN)nextr"   r#   StopIteration)r)   r9   s     r   rG   MultipartEncoder._next_part   s?    	%)$*:*:%;;A"   	A	s    //c              #     #    U R                   n[        U R                   S5      (       a#  [        U R                   R                  5       5      nU H  u  p#S nS nS n[	        U[        [
        45      (       a/  [        U5      S:X  a  Uu  pGO[        U5      S:X  a  Uu  pGnOUu  pGpVOUn[         R                  " X'UUS9nUR                  US9  Uv   M     g 7f)Nitemsr      )namedatafilenameheaders)content_type)	r   hasattrlistrV   
isinstancetupler/   RequestFieldmake_multipart)	r)   _fieldskv	file_name	file_typefile_headersfile_pointerfields	            r   _iter_fieldsMultipartEncoder._iter_fields   s     ++4;;((4;;,,./GDAIIL!dE]++q6Q;./+I|Vq[9:6IYGHDIY ''Q1:0<>E   i 8K% s   CCc                     U R                   nU R                  5        Vs/ sH  n[        R                  X!5      PM     snU l        [        U R                  5      U l        gs  snf )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.
N)r   rk   Part
from_fieldr    r!   r"   )r)   encfs      r   r'   MultipartEncoder._prepare_parts   sN     mm7;7H7H7JK7J!dooa-7JK


+ Ls   A c                 8    U R                   R                  U5      $ )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_writes     r   rI   MultipartEncoder._write   s     ||"">22r   c                 8    U R                  U R                  5      $ )z,Write the boundary to the end of the buffer.)rI   r   r.   s    r   r(    MultipartEncoder._write_boundary  s    {{41122r   c                     [        U R                  5         U R                  R                  SS5        U R                  R                  S5        SSS5        g! , (       d  f       g= f)z?Write the bytes necessary to finish a multipart/form-data body.r   s   --
N)resetr&   seekwriter.   s    r   rJ   (MultipartEncoder._write_closing_boundary  sL    4<< LLb!$LLy) !  !  s   8A
A%c                 J    U R                  [        XR                  5      5      $ )z/Write the current part's headers to the buffer.)rI   r   r   )r)   r[   s     r   _write_headersMultipartEncoder._write_headers  s    {{;w>??r   c                 J    [        SR                  U R                  5      5      $ )Nz multipart/form-data; boundary={})strr   r   r.   s    r   r\   MultipartEncoder.content_type  s#    .55d6I6IJ 	r   c                 "    U R                  5       $ )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.   s    r   	to_stringMultipartEncoder.to_string  s    $ yy{r   c                     U R                   (       a  U R                  R                  U5      $ UnUS:w  a  Ub  U R                  [	        U5      5      nU R                  U5        U R                  R                  U5      $ )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
rE   )r   r&   r   rB   intrN   )r)   sizebytes_to_loads      r   r   MultipartEncoder.read+  sg     ==<<$$T**B=#< 77D	BM

=!||  &&r   )r&   r#   r   r"   r$   r   r   r   r   r   r    Nutf-8rE   )r   r   r   r   r   r*   propertyr/   r2   r-   rB   rN   rG   rk   r'   rI   r(   rJ   r   r\   r   r   r   r
   r   r   r   r      sx    ;z)V 5 5&>+*"*0,33@  
('r   r   c                     U $ rQ   r
   )monitors    r   IDENTITYr   >  s    Nr   c                   Z    \ rS rSrSrS
S jr\  SS j5       r\S 5       r	S r
SS jrS	rg)MultipartEncoderMonitoriB  a  
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                 |    Xl         U=(       d    [        U l        SU l        U R                   R                  U l        g Nr   )encoderr   callback
bytes_readr/   )r)   r   r   s      r   r*    MultipartEncoderMonitor.__init__u  s1     !,H  <<##r   c                 *    [        XU5      nU " XT5      $ rQ   )r   )clsr   r   r   r   r   s         r   from_fields#MultipartEncoderMonitor.from_fields  s     #6X>7%%r   c                 .    U R                   R                  $ rQ   )r   r\   r.   s    r   r\   $MultipartEncoderMonitor.content_type  s    ||(((r   c                 "    U R                  5       $ rQ   r   r.   s    r   r   !MultipartEncoderMonitor.to_string  s    yy{r   c                     U R                   R                  U5      nU =R                  [        U5      -  sl        U R	                  U 5        U$ rQ   )r   r   r   r/   r   )r)   r   strings      r   r   MultipartEncoderMonitor.read  s9    ""4(3v;&dr   )r   r   r   r/   rQ   )Nr   Nr   )r   r   r   r   r   r*   classmethodr   r   r\   r   r   r   r
   r   r   r   r   B  sE    /b$ 9@!& &
 ) )r   r   c                 X    U b&  [        U [        5      (       d  U R                  U5      $ U $ )a"  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
)r_   bytesencode)r   r   s     r   r   r     s)     Nj77}}X&&Mr   c                 >    [        U S5      (       a  U $ [        X5      $ )z4Coerce the data to an object with a ``read`` method.r   )r]   r%   rY   r   s     r   readable_datar     s    tV((r   c                    [        U S5      (       a  [        U 5      $ [        U S5      (       a  U R                  $ [        U S5      (       a1   U R                  5       n[        R                  " U5      R
                  $ [        U S5      (       a  [        U R                  5       5      $ g ! [        R                   a     NAf = f)N__len__r/   filenogetvalue)	r]   r/   r   osfstatst_sizeioUnsupportedOperationr   )or   s     r   r7   r7     s    q)1vq%uuq(	,XXZF 88F#+++q*1::<    && 		s   B' 'B>=B>c              #   |   #    U R                  5       nU R                  SS5        Sv   U R                  US5        g7f)zKeep 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tellr|   )bufferoriginal_positions     r   r{   r{     s3      
KK1	
KK!1%s   :<c                     [        U [        5      (       dc  [        U S5      (       a  [        U R                  5       U5      $ [        U S5      (       a  [	        U 5      $ [        U S5      (       d  [        X5      $ U $ )z5Ensure that every object's __len__ behaves uniformly.r   r   r   )r_   r%   r]   r   FileWrapperr   s     r   coerce_datar     sd    dM**4$$ (;;4""t$$tV$$ 00Kr   c                 n    [        U S5      (       a  [        U R                  " 5       5      $ [        U 5      $ )NrV   )r]   r^   rV   r   s    r   to_listr     s*    vwFLLN##<r   c                   6    \ rS rSrS r\S 5       rS rS rSr	g)rn   i  c                     Xl         X l        SU l        [        U R                   5      [	        U R                  5      -   U l        g )NT)r[   bodyheaders_unreadr/   r7   )r)   r[   r   s      r   r*   Part.__init__  s2    	"t||$y';;r   c                 r    [        UR                  5       U5      n[        UR                  U5      nU " X45      $ )z8Create a part from a Request Field generated by urllib3.)r   render_headersr   rY   )r   rj   r   r[   r   s        r   ro   Part.from_field  s4     e224h?5::x07!!r   c                     SnU R                   (       a  U[        U R                  5      -  nU[        U R                  5      -   S:  $ )zDetermine if there are bytes left to write.

:returns: bool -- ``True`` if there are bytes left to write, otherwise
    ``False``
r   )r   r/   r[   r7   r   )r)   to_reads     r   rH   Part.bytes_left_to_write  s>     s4<<((G)DII..!33r   c                 |   SnU R                   (       a$  X1R                  U R                  5      -  nSU l         [        U R                  5      S:  ak  US:X  d  X2:  a`  UnUS:w  a  X#-
  nX1R                  U R                  R                  U5      5      -  n[        U R                  5      S:  a  US:X  a  MY  X2:  a  M`  U$ )aZ  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   FrE   )r   rt   r[   r7   r   r   )r)   r   r   rM   amount_to_reads        r   rK   Part.write_to  s     }}T\\22G"'D		"Q&DBJ'.!Nrz!%}}TYY^^N%CDDG	 		"Q&DBJ'. r   )r   r[   r   r/   N)
r   r   r   r   r*   r   ro   rH   rK   r   r
   r   r   rn   rn     s%    < " "
4r   rn   c                   N   ^  \ rS rSrSU 4S jjrS r\S 5       rS rS r	Sr
U =r$ )	r%   i  c                 B   > [        X5      n[        [        U ]  U5        g rQ   )r   superr%   r*   )r)   r   r   	__class__s      r   r*   CustomBytesIO.__init__  s    V.mT+F3r   c                     U R                  5       nU R                  SS5        U R                  5       nU R                  US5        U$ )Nr   r   r   )r)   current_poslengths      r   _get_endCustomBytesIO._get_end  s8    iik		!Q		+q!r   c                 F    U R                  5       nXR                  5       -
  $ rQ   )r   r   r)   r   s     r   r/   CustomBytesIO.len!  s    		##r   c                 t    [        U 5         U R                  U5      nS S S 5        U$ ! , (       d  f       W$ = frQ   )r{   r}   )r)   r   rM   s      r   rt   CustomBytesIO.append&  s.    4[jj'G  [s   (
7c                     [        U 5      nU R                  5       U-
  nX!:  aV  U R                  5       nU R                  SS5        U R	                  5         U R                  U5        U R                  SS5        g g r   )r7   r   r   r|   truncater}   )r)   
to_be_readalready_read	old_bytess       r   rF   CustomBytesIO.smart_truncate+  s`    t_
}}3%		IIIaOMMOJJy!IIaO &r   r
   r   )r   r   r   r   r*   r   r   r/   rt   rF   r   __classcell__)r   s   @r   r%   r%     s0    4 $ $
	 	r   r%   c                   4    \ rS rSrS r\S 5       rSS jrSrg)r   i7  c                     Xl         g rQ   fd)r)   file_objects     r   r*   FileWrapper.__init__8  s    r   c                 b    [        U R                  5      U R                  R                  5       -
  $ rQ   )r7   r   r   r.   s    r   r/   FileWrapper.len;  s     !DGGLLN22r   c                 8    U R                   R                  U5      $ rQ   )r   r   r   s     r   r   FileWrapper.read?  s    ww||F##r   r   Nr   )	r   r   r   r   r*   r   r/   r   r   r
   r   r   r   r   7  s      3 3$r   r   c                   .    \ rS rSrSrSS jrS rS rSrg)	FileFromURLWrapperiC  a  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                     U=(       d    [         R                  " 5       U l        U R                  U5      n[	        UR
                  S   5      U l        UR                  U l        g )Ncontent-length)	requestsSessionsession_request_for_filer   r[   r/   rawraw_data)r)   file_urlr   requested_files       r   r*   FileFromURLWrapper.__init__q  sL    4("2"2"4//9~--.>?@&**r   c                 
   U R                   R                  USS9nUR                  R                  SS5      nUc  SR                  US9n[	        U5      eUR                  5       (       d  SR                  US9n[	        U5      eU$ )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   getr[   r   r   isdigit)r)   r   responsecontent_length	error_msgs        r   r   $FileFromURLWrapper._request_for_filew  s    <<##HT#:!))--.>E!DDJF  EK E" 
 (	22''))00680D  (	22r   c                     US:  a  UOU R                   nU R                  R                  U5      =(       d    SnU =R                   U(       a  [        U5      OS-  sl         U$ )zRead file in chunks.r   r   )r/   r   r   )r)   
chunk_sizechunks      r   r   FileFromURLWrapper.read  sG    #-?Z
"":.5#%CJQ.r   )r/   r   r   rQ   )	r   r   r   r   r   r*   r   r   r   r
   r   r   r   r   C  s    +Z+&r   r   )r   
contextlibr   r   uuidr   r   _compatr   	Exceptionr   objectr   r   r   r   r   r7   contextmanagerr{   r   r   rn   BytesIOr%   r   r   r
   r   r   <module>r     s     	 	   $I $c'v c'L	Rf Rj
)!( 
& 
&/6 /dBJJ D	$& 	$L Lr   