o
    tBh>                     @   s   d dl Z d dlZd dlZd dl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mZmZ d dlmZ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!m"Z"m#Z#m$Z$ e%e&Z'G dd deZ(dS )    N)Any
CollectionDictListOptionalTupleTypeUnion)DocumentNodeExecutionResult	print_ast)HTTPAdapterRetry)AuthBase)RequestsCookieJar)MultipartEncoder)	Transport   )GraphQLRequest)extract_files   )TransportAlreadyConnectedTransportClosedTransportProtocolErrorTransportServerErrorc                   @   s^  e Zd ZU dZejfZeee	 df e
d< dZddddddddd	ef
d
edeeee	f  deeeee	f ef  dee dedee deeef dedededee de	fddZdd Z					d@dedeeee	f  dee dee deeee	f  ded efd!d"Z		dAd#ee dee deeee	f  d ee fd$d%Zd&eee	f d efd'd(Zd)e	d dfd*d+Zd)eeee	f  d dfd,d-Z d)eeee	f  d dfd.d/Z!d#ee d)eeee	f  d dfd0d1Z"d2ed3ed dfd4d5Z#d6e$j%d e	fd7d8Z&		dAd#ee dee deeee	f  d eee	f fd9d:Z'd;ed eee	f fd<d=Z(d>d? Z)dS )BRequestsHTTPTransportz:ref:`Sync Transport <sync_transports>` used to execute GraphQL queries
    on remote servers.

    The transport uses the requests library to send HTTP POST requests.
    .file_classes)i  i  i  i  i  NTr   POSTg?urlheaderscookiesauthuse_jsontimeoutverifyretriesmethodretry_backoff_factorretry_status_forcelistkwargsc                 K   sX   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _d| _d| _dS )a  Initialize the transport with the given request parameters.

        :param url: The GraphQL server URL.
        :param headers: Dictionary of HTTP Headers to send with the :class:`Request`
            (Default: None).
        :param cookies: Dict or CookieJar object to send with the :class:`Request`
            (Default: None).
        :param auth: Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth
            (Default: None).
        :param use_json: Send request body as JSON instead of form-urlencoded
            (Default: True).
        :param timeout: Specifies a default timeout for requests (Default: None).
        :param verify: Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. (Default: True).
        :param retries: Pre-setup of the requests' Session for performing retries
        :param method: HTTP method used for requests. (Default: POST).
        :param retry_backoff_factor: A backoff factor to apply between attempts after
            the second try. urllib3 will sleep for:
            {backoff factor} * (2 ** ({number of previous retries}))
        :param retry_status_forcelist: A set of integer HTTP status codes that we
            should force a retry on. A retry is initiated if the request method is
            in allowed_methods and the response status code is in status_forcelist.
            (Default: [429, 500, 502, 503, 504])
        :param kwargs: Optional arguments that ``request`` takes.
            These can be seen at the `requests`_ source code or the official `docs`_

        .. _requests: https://github.com/psf/requests/blob/master/requests/api.py
        .. _docs: https://requests.readthedocs.io/en/master/
        N)r   r   r    r!   r"   default_timeoutr$   r%   r&   r'   r(   r)   sessionresponse_headers)selfr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)    r.   m/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/gql/transport/requests.py__init__%   s   -
zRequestsHTTPTransport.__init__c                 C   sb   | j d u r-t | _ | jdkr)tt| j| j| jd dd}dD ]}| j || qd S d S t	d)Nr   )totalbackoff_factorstatus_forcelistallowed_methods)max_retries)zhttp://zhttps://zTransport is already connected)
r+   requestsSessionr%   r   r   r'   r(   mountr   )r-   adapterprefixr.   r.   r/   connectc   s    


	zRequestsHTTPTransport.connectFdocumentvariable_valuesoperation_name
extra_argsupload_filesreturnc                    s|  | j stdt|}d|i}|r||d< | j| j| j|p| j| jd}	|r|dus,J t|| j	d\}
 |
|d< t
|}td| d	d
 t D } fdd
t D }t
|}td| ||d}| D ]"\}}t|d|}t|dd}|du r||f||< ql|||f||< qlt|d}||	d< |	d du ri |	d< ni |	d |	d< |j|	d d< n|r||d< | jrdnd}||	|< ttjrtdt
| |	| j |r|	| | j j| j| jfi |	}|j| _dtjdt fdd}z|
 }ttjrtd|j! W n t"y   ||d Y nw d|vr.d|vr.||d t#|$d|$d|$ddS ) a  Execute GraphQL query.

        Execute the provided document AST against the configured remote server. This
        uses the requests library to perform a HTTP POST request to the remote server.

        :param document: GraphQL query as AST Node object.
        :param variable_values: Dictionary of input parameters (Default: None).
        :param operation_name: Name of the operation that shall be executed.
            Only required in multi-operation documents (Default: None).
        :param timeout: Specifies a default timeout for requests (Default: None).
        :param extra_args: additional arguments to send to the requests post method
        :param upload_files: Set to True if you want to put files in the variable values
        :return: The result of execution.
            `data` is the result of executing the query, `errors` is null
            if no errors occurred, and is a non-empty array if an error occurred.
        Transport is not connectedqueryoperationNamer   r!   r    r#   r$   N)	variablesr   rF   zoperations %sc                 S   s   i | ]
\}}t ||gqS r.   str.0ipathr.   r.   r/   
<dictcomp>   s    z1RequestsHTTPTransport.execute.<locals>.<dictcomp>c                    s   i | ]\}}t | | qS r.   rG   rI   filesr.   r/   rM      s    zfile_map %s)
operationsmapnamecontent_type)fieldsdatar   zContent-Typejson>>> %srespreasonc              
   S   sV   z|    W n tjy } z
tt||jj|d }~ww | j}td| d| )Nz(Server did not return a GraphQL result: : )	raise_for_statusr6   	HTTPErrorr   rH   responsestatus_codetextr   )rX   rY   eresult_textr.   r.   r/   raise_response_error   s   z;RequestsHTTPTransport.execute.<locals>.raise_response_error<<< %sNot a JSON answererrors$No "data" or "errors" keys in answer
extensionsre   rU   rg   )%r+   r   r   r   r!   r    r*   r$   r   r   rV   dumpslogdebug	enumerateitemsgetattrr   rS   r"   isEnabledForloggingINFOinfoupdater)   requestr&   r   r,   r6   ResponserH   r_   	Exceptionr   get)r-   r<   r=   r>   r#   r?   r@   	query_strpayload	post_argsnulled_variable_valuesoperations_strfile_mapfile_streamsfile_map_strrT   kfrR   rS   rU   data_keyr]   rb   resultr.   rN   r/   executew   s   







zRequestsHTTPTransport.executereqsc                    s    j std j j j jfi  |||}|j _ |} 	|  
||  |  |  fdd|D S )a  Execute multiple GraphQL requests in a batch.

        Execute the provided requests against the configured remote server. This
        uses the requests library to perform a HTTP POST request to the remote server.

        :param reqs: GraphQL requests as a list of GraphQLRequest objects.
        :param timeout: Specifies a default timeout for requests (Default: None).
        :param extra_args: additional arguments to send to the requests post method
        :return: A list of results of execution.
            For every result `data` is the result of executing the query,
            `errors` is null if no errors occurred, and is a non-empty array
            if an error occurred.
        rB   c                       g | ]}  |qS r.   )_answer_to_execution_result)rJ   answerr-   r.   r/   
<listcomp>;      z7RequestsHTTPTransport.execute_batch.<locals>.<listcomp>)r+   r   rt   r&   r   _build_batch_post_argsr   r,   _extract_response_validate_answer_is_a_list)_validate_num_of_answers_same_as_requests _validate_every_answer_is_a_dict)_validate_data_and_errors_keys_in_answers)r-   r   r#   r?   r]   answersr.   r   r/   execute_batch  s   



z#RequestsHTTPTransport.execute_batchr   c                 C   s    t |d|d|ddS )Nre   rU   rg   rh   )r   rw   )r-   r   r.   r.   r/   r   =  s
   z1RequestsHTTPTransport._answer_to_execution_resultresultsc                 C   s"   t |ts| t|d d S d S )NzAnswer is not a list)
isinstancelist_raise_invalid_resultrH   )r-   r   r.   r.   r/   r   D  s   
z0RequestsHTTPTransport._validate_answer_is_a_listc                 C   s.   |D ]}d|vrd|vr|  t|d qd S )Nre   rU   rf   )r   rH   r-   r   r   r.   r.   r/   r   K  s   z?RequestsHTTPTransport._validate_data_and_errors_keys_in_answersc                 C   s(   |D ]}t |ts| t|d qd S )NzNot every answer is dict)r   dictr   rH   r   r.   r.   r/   r   U  s
   
z6RequestsHTTPTransport._validate_every_answer_is_a_dictc                 C   s(   t |t |kr| t|d d S d S )NzInvalid answer length)lenr   rH   )r-   r   r   r.   r.   r/   r   Z  s   z?RequestsHTTPTransport._validate_num_of_answers_same_as_requestsra   rY   c                 C   s   t d| d| )Nz.Server did not return a valid GraphQL result: rZ   )r   )r-   ra   rY   r.   r.   r/   r   e  s   z+RequestsHTTPTransport._raise_invalid_resultr]   c              
   C   s   z|   | }ttjrtd|j W |S W |S  tj	y2 } z
t
t||jj|d }~w tyD   | t|jd Y |S w )Nrc   rd   )r[   rV   rj   ro   rp   rq   rr   r_   r6   r\   r   rH   r]   r^   rv   r   )r-   r]   r   r`   r.   r.   r/   r   l  s   	z'RequestsHTTPTransport._extract_responsec                    s    j  j j|p
 j jd} jrdnd} fdd|D ||< ttj	r2t
dt||  | j |r?|| |S )NrE   rV   rU   c                    r   r.   )_build_data)rJ   reqr   r.   r/   r     r   z@RequestsHTTPTransport._build_batch_post_args.<locals>.<listcomp>rW   )r   r!   r    r*   r$   r"   rj   ro   rp   rq   rr   rV   ri   rs   r)   )r-   r   r#   r?   rz   r   r.   r   r/   r   |  s   
z,RequestsHTTPTransport._build_batch_post_argsr   c                 C   s6   t |j}d|i}|jr|j|d< |jr|j|d< |S )NrC   rD   rF   )r   r<   r>   r=   )r-   r   rx   ry   r.   r.   r/   r     s   


z!RequestsHTTPTransport._build_datac                 C   s   | j r| j   d| _ dS dS )z2Closing the transport by closing the inner sessionN)r+   closer   r.   r.   r/   r     s   

zRequestsHTTPTransport.close)NNNNF)NN)*__name__
__module____qualname____doc__ioIOBaser   r   r   r   __annotations___default_retry_codesrH   r   r   r	   r   r   boolintfloatr   r0   r;   r
   r   r   r   r   r   r   r   r   r   r   r   r6   ru   r   r   r   r   r.   r.   r.   r/   r      s   
 
	

>
 "
(




r   ))r   rV   rp   typingr   r   r   r   r   r   r   r	   r6   graphqlr
   r   r   requests.adaptersr   r   requests.authr   requests.cookiesr   #requests_toolbelt.multipart.encoderr   gql.transportr   graphql_requestr   utilsr   
exceptionsr   r   r   r   	getLoggerr   rj   r   r.   r.   r.   r/   <module>   s     (
