3
gVO              	   @   sR  d dl Zd dlZd dlZ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
mZ d dlmZmZmZmZmZ ddlmZ ddlmZ ddlmZ ejdkrd dlZndZd
d ZeedddZG dd dZG dd dZG dd dZeZ eddeed eedef gef dddZ!ededef eed edddZ!d ddZ!dS )!    N)FutureThreadPoolExecutor)AnyCallableDictOptionaloverload   )get_running_loop)CurrentThreadExecutor)Local      c             C   s^   xX| D ]P}y&|j  | j |kr.|j| j | W q tk
rT   |j| j | Y qX qW d S )N)getsetLookupError)contextZcvar r   J/var/www/tester-filtro-web/env/lib/python3.6/site-packages/asgiref/sync.py_restore_context   s    
r   )funcreturnc             C   sP   t jdkrtj| S xtj| r(| j} qW xt| tj	r@| j
} q,W tj| S d S )Nr      )r   r   )sysversion_infoasyncioiscoroutinefunctioninspectismethod__func__
isinstance	functoolspartialr   )r   r   r   r   _iscoroutinefunction_or_partial!   s    



r#   c               @   s>   e Zd ZdZdd Zer*dd Zdd Zndd Zd	d Zd
S )ThreadSensitiveContexta  Async context manager to manage context for thread sensitive mode

    This context manager controls which thread pool executor is used when in
    thread sensitive mode. By default, a single thread pool executor is shared
    within a process.

    In Python 3.7+, the ThreadSensitiveContext() context manager may be used to
    specify a thread pool per context.

    In Python 3.6, usage of this context manager has no effect.

    This context manager is re-entrant, so only the outer-most call to
    ThreadSensitiveContext will set the context.

    Usage:

    >>> import time
    >>> async with ThreadSensitiveContext():
    ...     await sync_to_async(time.sleep, 1)()
    c             C   s
   d | _ d S )N)token)selfr   r   r   __init__F   s    zThreadSensitiveContext.__init__c                s6   yt jj  W n" tk
r0   t jj| | _Y nX | S )N)SyncToAsyncthread_sensitive_contextr   r   r   r%   )r&   r   r   r   
__aenter__K   s
    z!ThreadSensitiveContext.__aenter__c                s6   | j s
d S tjj| d }|r$|j  tjj| j  d S )N)r%   r(   context_to_thread_executorpopshutdownr)   reset)r&   excvaluetbexecutorr   r   r   	__aexit__S   s    z ThreadSensitiveContext.__aexit__c                s   | S )Nr   )r&   r   r   r   r*   ^   s    c                s   d S )Nr   )r&   r/   r0   r1   r   r   r   r3   a   s    N)__name__
__module____qualname____doc__r'   contextvarsr*   r3   r   r   r   r   r$   0   s   
r$   c               @   sJ   e Zd ZU dZi Zde ZdddZdd Zdd	 Z	d
d Z
dd ZdS )AsyncToSynca  
    Utility class which turns an awaitable that only works on the thread with
    the event loop into a synchronous callable that works in a subthread.

    If the call stack contains an async loop, the code runs there.
    Otherwise, the code runs in a new loop in a new thread.

    Either way, this thread then pauses and waits to run any thread_sensitive
    code called from further down the call stack using SyncToAsync, before
    finally exiting once the async task returns.
    z,Dict[asyncio.Task[object], threading.Thread]Fc             C   s   t | st| rtjd || _y| jj| _W n tk
rF   Y nX |rTd | _nXyt | _W nJ t	k
r   t
tjdd }|r|tj krt
tjdd | _nd | _Y nX d S )Nz4async_to_sync was passed a non-async-marked callablemain_event_loop_pidmain_event_loop)callabler#   warningswarn	awaitable__self__AttributeErrorr;   r
   RuntimeErrorgetattrr(   threadlocalosgetpid)r&   r?   Zforce_new_loopr:   r   r   r   r'   y   s$    
zAsyncToSync.__init__c             O   sJ  y
t  }W n tk
r   Y nX |j r0tdtd k	rDtj g}nd }t }tj }t| j	drl| j	j
}nd }t }|| j	_
z| j||||tj |}	| jo| jj stj }
tdd}|j| j|
|	}|r|j| |j  n"| jj| jj|	 |r|j| W d t| j	dr| j	`
|r*|| j	_
td k	r@t|d  X |j S )NznYou cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.currentr	   )max_workersr   )r
   rB   
is_runningr8   copy_contextr   	threadingcurrent_threadhasattr	executorsrG   r   	main_wrapr   exc_infor;   r   new_event_loopr   submit_run_event_loopZrun_until_futureresultcall_soon_threadsafecreate_taskr   )r&   argskwargsZ
event_loopr   call_resultsource_threadZold_current_executorZcurrent_executorr?   loopZloop_executorZloop_futurer   r   r   __call__   sN    





zAsyncToSync.__call__c                s   t j| z|j| W dztjd
kr2t j| nt jj| x D ]}|j  qDW  fdd}|j|  x8 D ]0}|j rqr|j	 dk	rr|j
d|j	 |d qrW t|d	r|j|j  W d|j  t j| j X X dS )zP
        Runs the given event loop (designed to be called in a thread).
        Nr   r   r   c                  s   t j ddiI d H  d S )Nreturn_exceptionsT)r   gatherr   )tasksr   r   r^      s    z+AsyncToSync._run_event_loop.<locals>.gatherz(unhandled exception during loop shutdown)message	exceptiontaskshutdown_asyncgens)r   r   r   )r   set_event_looprun_until_completer   r   	all_tasksTaskcancel	cancelledra   call_exception_handlerrM   rc   closer;   )r&   r[   cororb   r^   r   )r_   r   rS      s.    




zAsyncToSync._run_event_loopc             C   s   t j| j|}t j|| jS )z*
        Include self for methods
        )r!   r"   r\   update_wrapperr?   )r&   parentobjtyper   r   r   r   __get__  s    zAsyncToSync.__get__c       
         s   |dk	rt |d  tj }|| j|< zyT|d rhy|d W qz tk
rd   | j||I dH }Y qzX n| j||I dH }W n, tk
r }	 z|j|	 W Y dd}	~	X nX |j| W d| j|= |dk	rtj	 |d< X dS )zs
        Wraps the awaitable with something that puts the result into the
        result/exception future.
        Nr   r	   )
r   r(   get_current_task
launch_mapBaseExceptionr?   set_exception
set_resultr8   rJ   )
r&   rW   rX   rY   rZ   rP   r   current_taskrT   er   r   r   rO     s"    
zAsyncToSync.main_wrapN)F)r4   r5   r6   r7   rr   r   rN   r'   r\   rS   rp   rO   r   r   r   r   r9   e   s   

I'r9   c               @   s   e Zd ZU dZdejkr8e Zeje	e
ejd d i Zdej Ze	ddZejdkrlejdZd	nd
Zd
ejdkrejdZdnd
Zd
ej Zddedef eed d
dddZdd Zdd Zdd Z e!dd Z"d
S )r(   a  
    Utility class which turns a synchronous callable into an awaitable that
    runs in a threadpool. It also sets a threadlocal inside the thread so
    calls to AsyncToSync can escape it.

    If thread_sensitive is passed, the code will run in the same thread as any
    outer code. This is needed for underlying Python code that is not
    threadsafe (for example, code which handles SQLite database connections).

    If the outermost program is async (i.e. SyncToAsync is outermost), then
    this will be a dedicated single sub-thread that all sync code runs in,
    one after the other. If the outermost program is sync (i.e. AsyncToSync is
    outermost), this will just be the main thread. This is achieved by idling
    with a CurrentThreadExecutor while AsyncToSync is blocking its sync parent,
    rather than just blocking.

    If executor is passed in, that will be used instead of the loop's default executor.
    In order to pass in an executor, thread_sensitive must be set to False, otherwise
    a TypeError will be raised.
    ZASGI_THREADS)rH   z,Dict[threading.Thread, asyncio.Task[object]]r	   r   r   r)   zcontextvars.ContextVar[str]Ndeadlock_contextzcontextvars.ContextVar[bool]z5weakref.WeakKeyDictionary[object, ThreadPoolExecutor]T.r   )r   thread_sensitiver2   r   c             C   s|   t | st|rtd|| _tj| | || _tjj	| _	|rP|d k	rPtd|| _
y|j| _W n tk
rv   Y nX d S )Nz4sync_to_async can only be applied to sync functions.z6executor must not be set when thread_sensitive is True)r<   r#   	TypeErrorr   r!   rm   _thread_sensitiver   
coroutines_is_coroutine	_executorr@   rA   )r&   r   ry   r2   r   r   r   r'   n  s    
zSyncToAsync.__init__c                sT  t  }| jrttjdr"tjj}q| jrj| jjd rj| jj }|| jkrT| j| }qt	dd}|| j|< q| j
r| j
jdrtdq| j}| j
r| j
jd n| j}td k	rtj }tj| jf||}|j}|f}i }n| j}zD|j|tj| j|| j tj |f||}	tj|	d dI d H }
W d td k	r:t| | j
rN| j
jd X |
S )NrG   r	   )rH   Fz9Single thread executor already being used, would deadlockT)timeout)r
   r{   rM   r9   rN   rG   r)   r   r+   r   rx   rB   single_thread_executorr   r~   r8   rJ   r!   r"   r   runrun_in_executorthread_handlerrq   r   rP   r   wait_forr   )r&   rW   rX   r[   r2   r)   r   childr   futureretr   r   r   r\     sT    




zSyncToAsync.__call__c             C   s   t j| j|S )z*
        Include self for methods
        )r!   r"   r\   )r&   rn   ro   r   r   r   rp     s    zSyncToAsync.__get__c       	      O   s   || j _tj | j _tj }tjj	||kr2d}n|| j|< d}z@|d rty|d W q~ t
k
rp   |||S X n
|||S W d|r| j|= X dS )zE
        Wraps the sync application with exception handling.
        FTr	   N)rD   r;   rE   rF   r:   rK   rL   r9   rr   r   rs   )	r&   r[   Zsource_taskrP   r   rW   rX   rL   Z
parent_setr   r   r   r     s     
zSyncToAsync.thread_handlerc               C   s:   y t tdrtj S tjj S W n tk
r4   dS X dS )zs
        Cross-version implementation of asyncio.current_task()

        Returns None if there is no task.
        rv   N)rM   r   rv   rg   rB   r   r   r   r   rq     s    
zSyncToAsync.get_current_task)r   r   )r   r   )TN)#r4   r5   r6   r7   rE   environr
   r[   set_default_executorr   intrr   rK   localrD   r   r   r   r8   Z
ContextVarr)   rx   weakrefWeakKeyDictionaryr+   r   r   boolr   r'   r\   rp   r   staticmethodrq   r   r   r   r   r(   0  s.   




 D!r(   Tr   .)r   ry   r2   r   c             C   s   d S )Nr   )r   ry   r2   r   r   r   sync_to_async  s    r   c             C   s   d S )Nr   )r   ry   r2   r   r   r   r     s    c                s$   | d kr fddS t |  dS )Nc                s   t |  dS )N)ry   r2   )r(   )f)r2   ry   r   r   <lambda>  s   zsync_to_async.<locals>.<lambda>)ry   r2   )r(   )r   ry   r2   r   )r2   ry   r   r     s    )r   r   )NTN)TN)NTN)"Zasyncio.coroutinesr   r!   r   rE   r   rK   r=   r   concurrent.futuresr   r   typingr   r   r   r   r   Zcompatibilityr
   Zcurrent_thread_executorr   r   r   r   r8   r   r   r#   r$   r9   r(   Zasync_to_syncr   r   r   r   r   <module>   sF   

5 L Q  "   