o
    .j+                     @  s   d dl mZ d dl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 dd	lmZ dd
lmZ ddlmZ ddlmZ ejrSddlmZmZmZmZmZ d dlmZ G dd dZG dd deZ dS )    )annotationsN   )DEFAULT_RETRIES)BaseAdapter)PreparedRequestResponse)MaxRetryError)BytesQueueBuffer)HTTPResponse)Timeout)Retry)CaseInsensitiveDict)	ProxyType	RetryTypeTLSClientCertTypeTLSVerifyTypeWSGIApp)BytesIOc                   @  sT   e Zd ZdZddd	Z	
	ddddZd d!ddZd"ddZd#ddZd$ddZ	d
S )%
_WSGIRawIOz@File-like wrapper around a WSGI response iterator for streaming.	generator#typing.Generator[bytes, None, None]headerslist[tuple[str, str]]returnNonec                 C  s$   || _ t | _d| _|| _d | _d S )NF)
_generatorr	   _buffer_closedr   	extension)selfr   r    r    U/home/thesage/.local/lib/python3.10/site-packages/niquests/extensions/sgi/__init__.py__init__   s
   
z_WSGIRawIO.__init__NTamt
int | Nonedecode_contentboolbytesc                 C  s   | j rdS |d u s|dk r"| jD ]}| j| q| jt| jS t| j|k rEz| jt| j W n	 ty=   Y nw t| j|k s)t| jdkrNdS | jt|t| jS )N    r   )	r   r   r   putgetlennextStopIterationminr   r#   r%   chunkr    r    r!   read   s    
z_WSGIRawIO.readintc                 c  s    	 |  |}|sdS |V  q)z$Iterate over chunks of the response.TN)r1   r/   r    r    r!   stream9   s   
z_WSGIRawIO.streamc                 C  s$   d| _ t| jdr| j  d S d S )NTclose)r   hasattrr   r4   r   r    r    r!   r4   A   s   z_WSGIRawIO.closetyping.Iterator[bytes]c                 C  s   | S Nr    r6   r    r    r!   __iter__F      z_WSGIRawIO.__iter__c                 C  s   |  d}|s	t|S )Ni    )r1   r-   )r   r0   r    r    r!   __next__I   s   
z_WSGIRawIO.__next__)r   r   r   r   r   r   )NT)r#   r$   r%   r&   r   r'   )T)r#   r2   r%   r&   r   r   r   r   )r   r7   )r   r'   )
__name__
__module____qualname____doc__r"   r1   r3   r4   r9   r;   r    r    r    r!   r      s    
	

r   c                      sv   e Zd ZdZefd/ fdd	Zd0ddZ									d1d2d$d%Zd3d&d'Zd4d(d)Z	d5d+d,Z
d6d-d.Z  ZS )7WebServerGatewayInterfacez:Adapter for making requests to WSGI applications directly.appr   max_retriesr   r   r   c                   s4   t    || _t|tr|| _dS t|| _dS )z
        Initialize the WSGI adapter.

        :param app: A WSGI application callable.
        :param max_retries: Maximum number of retries for requests.
        N)superr"   rB   
isinstancer   rC   from_int)r   rB   rC   	__class__r    r!   r"   S   s
   


z"WebServerGatewayInterface.__init__strc                 C     dS )Nz<WSGIAdapter />r    r6   r    r    r!   __repr__b   r:   z"WebServerGatewayInterface.__repr__FNTrequestr   r3   r&   timeout)int | float | tuple | TimeoutSauce | Noneverifyr   certTLSClientCertType | NoneproxiesProxyType | Noneon_post_connection*typing.Callable[[typing.Any], None] | Noneon_upload_body;typing.Callable[[int, int | None, bool, bool], None] | Noneon_early_response(typing.Callable[[Response], None] | Nonemultiplexedr   c                 C  s@  t |trt|dkr|d p|d }n|d }nt |tr$|jp#|j}| j}|jp+d}	 z| ||}W n* t	y_ } zz|j
||j|d}W n tyP    w |  W Y d}~q,d}~ww td|j|j|j|jd	}t|jd
}|||j|rz|j
||j|d}W n ty   |jr | Y S w || q,|S )z/Send a PreparedRequest to the WSGI application.r      r   GETT)errorNr(   )bodyr   statusrequest_methodrequest_urlzRetry-After)response)rE   tupler+   TimeoutSaucetotalconnect_timeoutrC   method_do_send	Exception	incrementurlr   sleepBaseHTTPResponser   status_coder&   r*   is_retryraise_on_status)r   rL   r3   rM   rO   rP   rR   rT   rV   rX   rZ   retriesrg   rb   errbase_responsehas_retry_afterr    r    r!   sende   sP   



	
zWebServerGatewayInterface.sendc                   s  ddl m} ddlm} ||j}|jdkrd}nd}|j}|j|j d| dd|_| |}||_d	g  dd fdd}| ||fdd}	||	 }
t	 }|_
t |_||_||_|jdd|_ttg  }|
|_||_d|_d|_|S )zCHandle SSE requests by wrapping the WSGI response with SSE parsing.r   urlparse   )WSGISSEExtensionssehttpshttpz://Nr_   rI   r   r   c                      t | ddd | d S N rx   r   r2   splitr_   r   exc_inforesponse_headersrn   r    r!   start_response      z>WebServerGatewayInterface._do_send_sse.<locals>.start_responsec                	   3  @    z E d H  W t  dr   d S d S t  dr   w w Nr4   r5   r4   r    resultr    r!   generate      

z8WebServerGatewayInterface._do_send_sse.<locals>.generatecontent-typeutf-8Fr8   r_   rI   r   r   )urllib.parserw   _ssery   rk   schemereplace_create_environrB   r   rn   r   r   rL   r*   encodingr   iterr   raw_content_content_consumed)r   rL   rw   ry   parsedhttp_schemeoriginal_urlenvironr   r   extrb   raw_ior    r   r   rn   r!   _do_send_sse   s8   

 


z&WebServerGatewayInterface._do_send_ssec              	     s$  ddl m} ||j}|jdv rtd|jdv r| |S | |}dg  dd fdd}| ||t }|_	t
 |_||_|j|_|jdd|_fdd}t|  |_|rgd|_d|_|S g }	zD ]}
|	|
 qlW tdr~  ntdr  w w d|	|_|S )z Perform the actual WSGI request.r   rv   )wswssz$WebSocket is not supported over WSGI)rz   psseNr_   rI   r   r   c                   r}   r~   r   r   r   r    r!   r      r   z:WebServerGatewayInterface._do_send.<locals>.start_responser   r   c                	   3  r   r   r   r    r   r    r!   r      r   z4WebServerGatewayInterface._do_send.<locals>.generateFr4   r(   r8   r   )r   rw   rk   r   NotImplementedErrorr   r   rB   r   rn   r   r   rL   r*   r   r   r   r   r   appendr5   r4   join)r   rL   r3   rw   r   r   r   rb   r   body_chunksr0   r    r   r!   rh      sH   








z"WebServerGatewayInterface._do_senddictc                 C  sR  ddl m}m} ||j}|jpd}t|tr|d}nt|tj	r9t|tt
ttfs9d}|D ]}||7 }q0|}|jd||jpBd|jpFd|jpJdt|jpV|jdkrUd	nd
dd|jp]dt|t dddtt|d}|jr|j D ]1\}	}
t|	tr|	n|	d}	|	 dd}|dkr|
|d< qu|dkr|
|d< qu|
|d| < qu|S )z2Create a WSGI environ dict from a PreparedRequest.r   )unquoterw   r(   r    /	localhostr{   i  P   zHTTP/1.1)rx   r   r|   TF)REQUEST_METHODSCRIPT_NAME	PATH_INFOQUERY_STRINGSERVER_NAMESERVER_PORTSERVER_PROTOCOLzwsgi.versionzwsgi.url_schemez
wsgi.inputzwsgi.errorszwsgi.multithreadzwsgi.multiprocesszwsgi.run_onceCONTENT_LENGTHzlatin-1-_CONTENT_TYPEr   HTTP_)r   r   rw   rk   r^   rE   rI   encodetypingIterabler'   	bytearrayrc   rg   pathqueryhostnameportr   r   r+   r   itemsdecodeupperr   )r   rL   r   rw   r   r^   tmpr0   r   keyvalue	key_upperr    r    r!   r     sH   






z)WebServerGatewayInterface._create_environc                 C  rJ   )zClean up adapter resources.Nr    r6   r    r    r!   r4   D  s   zWebServerGatewayInterface.close)rB   r   rC   r   r   r   )r   rI   )	FNTNNNNNF)rL   r   r3   r&   rM   rN   rO   r   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r&   r   r   )rL   r   r   r   )rL   r   r3   r&   r   r   )rL   r   r   r   r<   )r=   r>   r?   r@   r   r"   rK   ru   r   rh   r   r4   __classcell__r    r    rG   r!   rA   P   s$    

?
5
:1rA   )!
__future__r   r   	_constantr   adaptersr   modelsr   r   packages.urllib3.exceptionsr   packages.urllib3.responser	   r
   rm   packages.urllib3.utilr   rd   packages.urllib3.util.retryr   
structuresr   TYPE_CHECKINGr   r   r   r   r   ior   r   rA   r    r    r    r!   <module>   s     ;