
    K:g-8                        U d dl mZ d dlmZmZmZmZmZmZm	Z	m
Z
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mZ d d
lmZ d dlmZmZ d dlm Z  d dl!m"Z" d dl#m$Z$m%Z%m&Z&m'Z'm(Z(  e
d      Z)e	e*e*f   Z+ee,d<    G d d      Z-y)    )cached_property)	AnyDictIteratorListOptionalSequenceTupleTypeVarUnionN)Session)	TypeAlias)retrying)Base
Enterprise)options_to_json_and_paramsoptions_to_params)Table)UserAndScopesDictassert_typed_dict	Workspace)Bases)Url
UrlBuildercache_unless_forcedchunkedenterprise_onlyTTimeoutTuplec                      e Zd ZU dZdZdZdZdZdZe	e
edf      ed<   eed	<   eed
<   eed<    G d de      Z ee      Zddddddede	e   de	eeej.                  f      d	edef
dZedefd       Zej6                  deddfd       ZdefdZdefdZdedefdZ dddded ed!eddfd"Z!e"de#fd#       Z$d$e#jJ                  ddfd%Z&dd&d!ede'd   fd'Z(ded(ed)e)e
ee*f      ddfd*Z+dddded+ed ed!edd,f
d-Z,d.edefd/Z-	 	 	 	 dDd0ed1ed2e	e.eef      d3e	e
ee*f      d4e	e
ee*f      d5e	e
ee*f      de*fd6Z/d1ed7e*de*fd8Z0d1ed7e*de*fd9Z1d1ed7e*de*fd:Z2d1ed7e*de*fd;Z3d<e4jj                  de*fd=Z6	 	 	 	 dEd0ed1ed2e	e.eef      d3e	e
ee*f      d4e	e
ee*f      d>ede7e*   fd?Z8d@e)e9   de7e)e9      fdAZ:e;dBede<fdC       Z=y)FApia	  
    Represents an Airtable API. Implements basic URL construction,
    session and request management, and retrying logic.

    Usage:
        >>> api = Api('auth_token')
        >>> table = api.table('base_id', 'table_name')
        >>> records = table.all()
    v0g?
   i>  Nr   _basesendpoint_urlsessionuse_field_idsc                   ,    e Zd Z ed      Z ed      Zy)	Api._urlszmeta/whoamiz
meta/basesN)__name__
__module____qualname__r   whoamibases     O/var/www/html/lionshead/venv/lib/python3.12/site-packages/pyairtable/api/api.py_urlsr+   7   s    ]#L!r2   r4   Tzhttps://api.airtable.comF)timeoutretry_strategyr'   r)   api_keyr5   r6   c                    |du rt        j                         }|st               | _        nt        j                  |      | _        t        |      | _        || _        || _        || _	        y)a  
        Args:
            api_key: An Airtable API key or personal access token.
            timeout: A tuple indicating a connect and read timeout.
                e.g. ``timeout=(2,5)`` would configure a 2 second timeout for
                the connection to be established  and 5 seconds for a
                server read timeout. Default is ``None`` (no timeout).
            retry_strategy: An instance of
                `urllib3.util.Retry <https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html#urllib3.util.Retry>`_.
                If ``None`` or ``False``, requests will not be retried.
                If ``True``, the default strategy will be applied
                (see :func:`~pyairtable.retry_strategy` for details).
            endpoint_url: The API endpoint to use. Override this if you are using
                a debugging or caching proxy.
            use_field_ids: If ``True``, all API requests will return responses
                with field IDs instead of field names.
        TN)
r   r6   r   r(   _RetryingSessionr   r'   r5   r7   r)   )selfr7   r5   r6   r'   r)   s         r3   __init__zApi.__init__=   s[    4 T!%446N"9DL#44^DDL-*r2   returnc                     | j                   S )zM
        Airtable API key or access token to use on all connections.
        )_api_keyr:   s    r3   r7   zApi.api_keyc   s    
 }}r2   valuec                 ~    | j                   j                  j                  ddj                  |      i       || _        y )NAuthorizationz	Bearer {})r(   headersupdateformatr>   )r:   r@   s     r3   r7   zApi.api_keyj   s1    ##_k6H6H6O$PQr2   c                      y)Nz<pyairtable.Api>r1   r?   s    r3   __repr__zApi.__repr__o   s    !r2   c                 n    | j                  d| j                  j                        }t        t        |      S )z
        Return the current user ID and (if connected via OAuth) the list of scopes.
        See `Get user ID & scopes <https://airtable.com/developers/web/api/get-user-id-scopes>`_ for more information.
        GET)requesturlsr/   r   r   )r:   datas     r3   r/   z
Api.whoamir   s,    
 ||E499#3#34 !2D99r2   workspace_idc                     t        | |      S )Nr   )r:   rM   s     r3   	workspacezApi.workspacez   s    |,,r2   validateforcebase_idrQ   rR   c                    |r2| j                  |      j                  |      }| j                  |      S t        | |      S )aL  
        Return a new :class:`Base` instance that uses this instance of :class:`Api`.

        Args:
            base_id: |arg_base_id|
            validate: |kwarg_validate_metadata|
            force: |kwarg_force_metadata|

        Raises:
            KeyError: if ``validate=True`` and the given base ID does not exist.
        rR   )
_base_infobase_base_from_infor   )r:   rS   rQ   rR   infos        r3   rW   zApi.base}   s@    $ ???/44W=D''--D'""r2   c                     | j                   j                  }d| j                  d|      D cg c]  }|d   D ]  }|  c}}i}t        j                  ||       S c c}}w )zY
        Return a schema object that represents all bases available via the API.
        r0   rI   )rK   r0   iterate_requestsr   from_api)r:   urlpage	base_inforL   s        r3   rV   zApi._base_info   sl    
 iioo 11%==D!%gI !. =
 ~~dD))s   Ar_   c                 \    t        | |j                  |j                  |j                        S )N)namepermission_level)r   idra   rb   )r:   r_   s     r3   rX   zApi._base_from_info   s)    LL&77	
 	
r2   rU   c                ~    | j                  |      j                  D cg c]  }| j                  |       c}S c c}w )aH  
        Retrieve the base's schema and return a list of :class:`Base` instances.

        Args:
            force: |kwarg_force_metadata|

        Usage:
            >>> api.bases()
            [
                <pyairtable.Base base_id='appSW9...'>,
                <pyairtable.Base base_id='appLkN...'>
            ]
        rU   )rV   r0   rX   )r:   rR   rY   s      r3   r0   z	Api.bases   sB     48???3O3U3U
3U4D  &3U
 	
 
s   :ra   tablesc                 D    | j                  |      j                  ||      S )a  
        Create a base in the given workspace.

        See https://airtable.com/developers/web/api/create-base

        Args:
            workspace_id: The ID of the workspace where the new base will live.
            name: The name to give to the new base. Does not need to be unique.
            tables: A list of ``dict`` objects that conform to Airtable's
                `Table model <https://airtable.com/developers/web/api/model/table-model>`__.
        )rO   create_base)r:   rM   ra   re   s       r3   rg   zApi.create_base   s     " ~~l+77fEEr2   
table_namer   c                R    | j                  |||      }|j                  |||      S )a#  
        Build a new :class:`Table` instance that uses this instance of :class:`Api`.

        Args:
            base_id: |arg_base_id|
            table_name: The Airtable table's ID or name.
            validate: |kwarg_validate_metadata|
            force: |kwarg_force_metadata|
        rP   )rW   table)r:   rS   rh   rQ   rR   rW   s         r3   rj   z	Api.table   s-    " yy85yAzz*xuzEEr2   
componentsc                 :    | j                   | j                  z  |z  S )z
        Build a URL to the Airtable API endpoint with the given URL components,
        including the API version number.
        )r'   VERSION)r:   rk   s     r3   	build_urlzApi.build_url   s    
   4<</:==r2   methodr]   fallbackoptionsparamsjsonc                    i t        |xs i       |xs i }| j                  j                  t        j                  ||||            }|rs|j                         dk(  r`t        t        |j                              | j                  k\  r5t        |xs i       \  }}	| j                  |d   |d   i |	|xs i |      S | j                  j                  ||||      }
| j                  |
      S )a  
        Make a request to the Airtable API, optionally converting a GET to a POST if the URL exceeds the
        `maximum URL length <https://support.airtable.com/docs/enforcement-of-url-length-limit-for-web-api-requests>`__.

        Args:
            method: HTTP method to use.
            url: The URL we're attempting to call.
            fallback: The method and URL to use if we have to convert a GET to a POST.
            options: Airtable-specific query params to use while fetching records.
                See :ref:`Parameters` for valid options.
            params: Additional query params to append to the URL as-is.
            json: The JSON payload for a POST/PUT/PATCH/DELETE request.
        )r]   rr   rs   rI   r      )ro   r]   rr   rs   )r   r(   prepare_requestrequestsRequestupperlenstrr]   MAX_URL_LENGTHr   rJ   _process_response)r:   ro   r]   rp   rq   rr   rs   request_paramspreparedspare_paramsresponses              r3   rJ   zApi.request   s
   2
2.
|
 <<//%	
 %'C%&$*=*==!;GMr!JD,<<{QK9,96<R9	     <<''!	 ( 
 %%h//r2   kwargsc                 *     | j                   d|fi |S )zq
        Make a GET request to the Airtable API.
        See :meth:`~Api.request` for keyword arguments.
        rI   rJ   r:   r]   r   s      r3   getzApi.get)  s    
 t||E31&11r2   c                 *     | j                   d|fi |S )zr
        Make a POST request to the Airtable API.
        See :meth:`~Api.request` for keyword arguments.
        POSTr   r   s      r3   postzApi.post0  s    
 t||FC2622r2   c                 *     | j                   d|fi |S )zs
        Make a PATCH request to the Airtable API.
        See :meth:`~Api.request` for keyword arguments.
        PATCHr   r   s      r3   patchz	Api.patch7  s    
 t||GS3F33r2   c                 *     | j                   d|fi |S )zt
        Make a DELETE request to the Airtable API.
        See :meth:`~Api.request` for keyword arguments.
        DELETEr   r   s      r3   deletez
Api.delete>  s    
 t||Hc4V44r2   r   c                 :   	 |j                          |j                  sy |j	                         S # t        j                  j                  $ rN}	 |j	                         }d|v r"g |j
                  t        |d         |_        |# t        $ r Y |w xY wd }~ww xY w)Nerror)	raise_for_statusrw   
exceptions	HTTPErrorrs   argsrepr
ValueErrortext)r:   r   exc
error_dicts       r3   r}   zApi._process_responseE  s    	%%' }}}} "",, 		F%]]_
 j(EE4
70C+DECHI   I			s3   / BB(B	BBBBBoffset_fieldc              #      K   |xs i }|xs i }dt         t        t        f   dt        t           ffd}	 | j	                  |||||      }| t        |t              sy ||      x}	syi ||	i}?w)a  
        Make one or more requests and iterates through each result.

        If the response payload contains an 'offset' value, this method will perform
        another request with that offset value as a parameter (query params for GET,
        body payload for POST/PATCH/etc).

        If the response payload is not a 'dict', it will be yielded as normal
        and the method will return.

        Args:
            method: HTTP method to use.
            url: The URL we're attempting to call.
            fallback: The method and URL to use if we have to convert a GET to a POST.
            options: Airtable-specific query params to use while fetching records.
                See :ref:`Parameters` for valid options.
            params: Additional query params to append to the URL as-is.
            offset_field: The key to use in the API response to determine whether
                there are additional pages to retrieve.
        r   r<   c                     | j                  d      xs | }j                  d      }|r&|j                  |j                  d            x}sy |r&t        |      S )N
pagination.r   )r   splitpopr{   )r   r@   field_namesr   s      r3   _get_offset_fieldz/Api.iterate_requests.<locals>._get_offset_fieldx  sZ    LL.:(E&,,S1K!&;??1+=!>>>  u:r2   )ro   r]   rp   rq   rr   N)r   r{   r   r   rJ   
isinstancedict)
r:   ro   r]   rp   rq   rr   r   r   r   offsets
         `   r3   r[   zApi.iterate_requestsX  s     : -R2	S#X 	8C= 	 ||! $ H Nh-/99F977,7G s   A3A6iterablec                 .    t        || j                        S )z
        Iterate through chunks of the given sequence that are equal in size
        to the maximum number of records per request allowed by the API.
        )r   MAX_RECORDS_PER_REQUEST)r:   r   s     r3   r   zApi.chunked  s    
 x!=!=>>r2   enterprise_account_idc                     t        | |      S )zE
        Build an object representing an enterprise account.
        r   )r:   r   s     r3   
enterprisezApi.enterprise  s    
 $ 566r2   )NNNN)NNNr   )>r,   r-   r.   __doc__rm   	API_LIMITr   r|   r&   r   r   r{   __annotations__r   r   boolr   r4   r   rK   r!   r   r   Retryr;   propertyr7   setterrG   r   r/   r   rO   rW   r   r   rV   InforX   r   r0   r	   r   rg   rj   rn   r
   rJ   r   r   r   r   rw   Responser}   r   r[   r    r   r   r   r   r1   r2   r3   r#   r#      s    GI ! N +/FHT#v+&'."
 " 5!D +/@D6#$+$+ ,'	$+
 !tX^^';!<=$+ $+ $+L    ^^S T  "# ":) :-c -i - ## 	#
 # 
#. *E * *
 
 
 &+ 
d 
tF| 
$FF F c3h(	F
 
F0 FF F
 F F 
F(>S >S > /3,0+/)-<0<0 <0 5c?+	<0
 $sCx.)<0 c3h(<0 tCH~&<0 
<0|2s 2c 2c 23 3s 3s 34 4 4 45# 5 5 5(*;*;  . /3,0+/$5858 58 5c?+	58
 $sCx.)58 c3h(58 58 
#58n? ?!0E ? 7 7
 7 7r2   r#   ).	functoolsr   typingr   r   r   r   r   r	   r
   r   r   rw   requests.sessionsr   typing_extensionsr   pyairtable.apir   pyairtable.api.baser   pyairtable.api.enterpriser   pyairtable.api.paramsr   r   pyairtable.api.tabler   pyairtable.api.typesr   r   pyairtable.api.workspacer   pyairtable.models.schemar   pyairtable.utilsr   r   r   r   r   r    intr!   r   r#   r1   r2   r3   <module>r      se    % W W W  % ' # $ 0 O & E . *  CLS/i )7 7r2   