o
    iG6                     @   s   d dl Z d dlZd dlZd dl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mZ d dlmZ d d	lmZmZmZmZmZmZmZ d d
lmZ d dlm Z  e!dZ"dd Z#G dd deZ$G dd dej%Z&dS )    N)defaultdict)aclosing)ThreadSensitiveContextsync_to_async)settings)signals)RequestAbortedRequestDataTooBig)base)FileResponseHttpRequestHttpResponseHttpResponseBadRequestHttpResponseServerError	QueryDictparse_cookie)set_script_prefix)cached_propertyzdjango.requestc                 C   s   t jrt jS | ddpdS )zM
    Return the script prefix to use from either the scope or a setting.
    	root_path )r   FORCE_SCRIPT_NAMEget)scope r   Y/var/www/html/formularioweb/env/lib/python3.10/site-packages/django/core/handlers/asgi.pyget_script_prefix   s   r   c                       sz   e Zd ZdZdZdd Zedd Z fddZd	d
 Z	dd Z
dd Zee	e
ZeeZedd Z fddZ  ZS )ASGIRequestzv
    Custom request subclass that decodes from an ASGI-standard request dict
    and wraps request body handling.
    <   c                 C   s  || _ d| _d| _d | _|d | _t|| _| jr#|d | j| _n|d | _| j d 	 | _
| j dd}t|tr@| }| j
|| j| jddd| _| j dro| j d d	 | jd
< | jd
 | jd< | j d d | jd< | j dr| j d d	 | jd< t| j d d | jd< n
d| jd< d| jd< tt}| j dg D ]-\}}|d}|dkrd}n|dkrd}n
d|	 dd }|d}|| | q| jdd | D  | | j || _d | _d S )NFpathmethodquery_stringr   T)REQUEST_METHODQUERY_STRINGSCRIPT_NAME	PATH_INFOzwsgi.multithreadzwsgi.multiprocessclientr   REMOTE_ADDRREMOTE_HOST   REMOTE_PORTserverSERVER_NAMESERVER_PORTunknown0headerslatin1zcontent-lengthCONTENT_LENGTHzcontent-typeCONTENT_TYPEzHTTP_%s-_c                 S   s   i | ]
\}}|d  |qS ),)join).0namevaluer   r   r   
<dictcomp>d   s    z(ASGIRequest.__init__.<locals>.<dictcomp>)r   _post_parse_error_read_startedresolver_matchr   r   script_nameremoveprefix	path_infoupperr   r   
isinstancebytesdecodeMETAstrr   listreplaceappendupdateitems_set_content_type_params_stream)selfr   	body_filer    _headersr8   r9   corrected_namer   r   r   __init__1   sV   



	




zASGIRequest.__init__c                 C   s   t | jd S )Nr"   )r   rE   rN   r   r   r   GETl   s   zASGIRequest.GETc                    s   | j dp
t  S )Nscheme)r   r   super_get_schemerS   	__class__r   r   rW   p   s   zASGIRequest._get_schemec                 C      t | ds	|   | jS )N_post)hasattr_load_post_and_filesr[   rS   r   r   r   	_get_posts      
zASGIRequest._get_postc                 C   s
   || _ d S N)r[   )rN   postr   r   r   	_set_postx   s   
zASGIRequest._set_postc                 C   rZ   )N_files)r\   r]   rc   rS   r   r   r   
_get_files{   r_   zASGIRequest._get_filesc                 C   s   t | jddS )NHTTP_COOKIEr   )r   rE   r   rS   r   r   r   COOKIES   s   zASGIRequest.COOKIESc                    s   t    | j  d S r`   )rV   closerM   rS   rX   r   r   rg      s   
zASGIRequest.close)__name__
__module____qualname____doc__body_receive_timeoutrR   r   rT   rW   r^   rb   rd   propertyPOSTFILESrf   rg   __classcell__r   r   rX   r   r   '   s    ;


r   c                       sx   e Zd ZdZeZdZ fddZdd Zdd Z	d	d
 Z
dd Zdd Zdd Z fddZdd Zedd Z  ZS )ASGIHandlerzHandler for ASGI requests.i   c                    s   t    | jdd d S )NT)is_async)rV   rR   load_middlewarerS   rX   r   r   rR      s   
zASGIHandler.__init__c              	      sr   |d dkrt d|d  t 4 I dH  | |||I dH  W d  I dH  dS 1 I dH s2w   Y  dS )zV
        Async entrypoint - parses the request and hands off to get_response.
        typehttpz5Django can only handle ASGI/HTTP connections, not %s.N)
ValueErrorr   handle)rN   r   receivesendr   r   r   __call__   s   
.zASGIHandler.__call__c              	      s  z
  |I dH }W n
 ty   Y dS w tt| tjj j|dI dH   ||\}}|du rL|	   
||I dH  t|j	 I dH  dS  fdd}t |t|||g}tj|tjdI dH  |D ]6}	|	 rz|	  W qo ty   Y qo ty   |	   w |	  z|	I dH  W qo tjy   Y qow z|d  }
W n tjy   tjj jdI dH  Y n
w t|
j	 I dH  |	  dS )zK
        Handles the ASGI request. Called via the __call__ method.
        N)senderr   c                    sB     | I d H }z ||I d H  W |S  tjy    Y |S w r`   )run_get_responsesend_responseasyncioCancelledError)requestry   responserS   r   r   process_request   s   z+ASGIHandler.handle.<locals>.process_request)return_whenr(   )r{   )	read_bodyr   r   r   r   request_startedasendrY   create_requestrg   r}   r   r~   create_tasklisten_for_disconnectwaitFIRST_COMPLETEDdoneresultAssertionErrorcancelr   request_finished)rN   r   rx   ry   rO   r   error_responser   taskstaskr   r   rS   r   rw      sT   zASGIHandler.handlec                    s0   | I dH }|d dkrt  J d|d  )z&Listen for disconnect from the client.Nrt   http.disconnectFz+Invalid ASGI message after request body: %s)r   )rN   rx   messager   r   r   r      s
   z!ASGIHandler.listen_for_disconnectc                    s0   |  |I dH }| j|_t|tr| j|_|S )zGet async response.N)get_response_asyncrY   _handler_classrB   r   
chunk_size
block_size)rN   r   r   r   r   r   r|      s   
zASGIHandler.run_get_responsec                    sn   t jtjdd}	 | I dH }|d dkr|  t d|v r(||d  |dd	s/nq
|d
 |S )z+Reads an HTTP body from an ASGI connection.zw+b)max_sizemodeTNrt   r   body	more_bodyFr   )	tempfileSpooledTemporaryFiler   FILE_UPLOAD_MAX_MEMORY_SIZErg   r   writer   seek)rN   rx   rO   r   r   r   r   r      s    
zASGIHandler.read_bodyc                 C   sh   z	|  ||dfW S  ty#   tjdt ddid dt f Y S  ty3   dtdddf Y S w )	z
        Create the Request object and returns either (request, None) or
        (None, response) if there is an error response.
        Nz Bad Request (UnicodeDecodeError)status_codei  )exc_infoextraz413 Payload too largei  )status)	request_classUnicodeDecodeErrorloggerwarningsysr   r   r	   r   )rN   r   rO   r   r   r   r     s   zASGIHandler.create_requestc                    s@   z	t  |||W S  ty   ttjrt nddd Y S w )z#Last-chance handler for exceptions.zInternal Server Errorz
text/plain)content_type)rV   handle_uncaught_exception	Exceptionr   r   DEBUG	traceback
format_exc)rN   r   resolverr   rX   r   r   r   #  s   
z%ASGIHandler.handle_uncaught_exceptionc              	      sj  g }|  D ]#\}}t|tr|d}t|tr|d}|t|t|f q|j D ]}|d|jddd	 f q0|d|j
|dI dH  |jrtt|4 I dH *}|2 z3 dH W }| |D ]\}	}
|d	|	d
dI dH  qjq_6 W d  I dH  n1 I dH sw   Y  |dd	iI dH  dS | |jD ]\}	}|d	|	| dI dH  qdS )z)Encode and send a response out over ASGI.asciir0   s
   Set-Cookier   )headerzhttp.response.start)rt   r   r/   Nzhttp.response.bodyT)rt   r   r   rt   )rK   rB   rF   encoderI   rC   cookiesvaluesoutputstripr   	streamingr   aiterchunk_bytescontent)rN   r   ry   response_headersr   r9   cr   partchunkr4   lastr   r   r   r}   /  sP   




(zASGIHandler.send_responsec                 c   sh    d}|s|dfV  dS |t |k r2|||| j  || j t |kfV  || j7 }|t |k sdS dS )z
        Chunks some data up so it can be sent in reasonable size messages.
        Yields (chunk, last_chunk) tuples.
        r   TN)lenr   )clsdatapositionr   r   r   r   f  s   

zASGIHandler.chunk_bytes)rh   ri   rj   rk   r   r   r   rR   rz   rw   r   r|   r   r   r   r}   classmethodr   rp   r   r   rX   r   rq      s    E7rq   )'r~   loggingr   r   r   collectionsr   
contextlibr   asgiref.syncr   r   django.confr   django.corer   django.core.exceptionsr   r	   django.core.handlersr
   django.httpr   r   r   r   r   r   r   django.urlsr   django.utils.functionalr   	getLoggerr   r   r   BaseHandlerrq   r   r   r   r   <module>   s&    $	
	e