a
    Dfl                  #   @  sj  d Z ddlm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ZddlZddlZddl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mZmZmZmZmZm Z  dd	l!m"Z"m#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- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZB ddlCmDZDmEZE ddlFmGZH ddlImJZK ddlLmMZN ddlOmPZP ddlQmRZR ddlSmTZTmUZUmVZV ddlWmXZX ddlYmZZZm[Z[m\Z\m]Z] ddl^m_Z_ d d!l`m`Z` d d"lambZbmcZc d d#ldmeZe d$d%lfm(Z(mgZg d$d&lhmiZimjZjmkZkmlZl d$d'lmmnZn d$d(lompZp d$d)lmqZqmrZrmsZs d$d*ltmuZu d$d+lvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZ d$d,lmZ d$d-lmZmZ eeZerdd.lmZ dd/lmZ dd0lmZmZ dd1lmZ dd2lmZ dd3lmZ d d4lmZ d d5lmZmZ d$d6lmZ e eeef Ze eeg ef e	jef Ze	je	jed7d8d9Zd:Zd;d;d<d=d>Zd;d?d;d@dAdBZdCd;d;dDdEdFdGdHdIZdJdKdLdMdNZee%j_dOdPdQdRZeje di fdSdTdUd;dVdWd;dXdYdZZdewdfd[d\d;d]d^d_d;d`dadbZddddeZG dfdg dgeBZAeAe$jj_AG dhdi diZG djdk dkZG dldm dmeeKeZJdneJfeDd< G dodp dpeHeZGdqeGfeDdr< G dsdt dteeNZMdneMfeEd< eMe$jj&_Mdudv Zee$jj&_ejdwkrve&jdxkrvee eju rvdyejvr\dzejvshd{ejv rvee  G d|d} d}e\Zddd?ddddEdEddEdEdEdEddddZG dd de[Zdd Zdddddcdcddcd~dci dddddi dddddddddddddcdcfdd?ddddEdEdEdEdDdEdd;dddddddddddddddddddEdgd!ddZG dd dejÃZdS )z0
Utilities for creating bokeh Server instances.
    )annotationsN)contextmanager)partialwraps)escape)FunctionType
MethodType)TYPE_CHECKINGAnyCallableDictMappingOptionalUnion)urljoinurlparse)Application)FunctionHandler)serialize_json)AUTOLOAD_JSFILEMACROS)silence)EMPTY_LAYOUT)Script)script_for_render_items)
RenderItem)wrap_in_script_tag)CustomJS)Server)per_app_patternstoplevel_patterns)AutoloadJsHandler)
DocHandler)RootHandler)StaticHandler)make_id)generate_jwt_tokengenerate_session_idget_token_payload)IOLoop)	HTTPErrorRequestHandlerStaticFileHandlerauthenticated)WSGIContainer   config)edit_readonlyfullpath)warn   )r    build_single_handler_application)_cleanup_docinit_docunlocked	with_lock)LivenessHandler)LOADING_INDICATOR_CSS_CLASS)LOG_SESSION_CREATEDLOG_SESSION_DESTROYEDLOG_SESSION_LAUNCHING)record_modules)
BASE_TEMPLATECDN_DISTCOMPONENT_PATHERROR_TEMPLATE
LOCAL_DIST	Resources_envbundle_resourcespatch_model_cssresolve_custom_path)generate_session)
set_curdocstate)Bundle)ID)DocJsonDocument)BokehSessionContext)ServerSession)TemplateBaseTemplate)ViewableViewer)Location..Z
_templatesz
index.htmlzPanel Applicationstr)urlreturnc                 C  s   |  dr| dd } | S )Nhttpz//r6   )
startswithsplit)r]    rb   \/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/panel/io/server.py_origin_urlk   s    
rd   int)r]   portr^   c                 C  s@   |  dr$d| ddd |df S d| dd |df S d S )Nr_   z%s:%d%s:r6   r   /zhttp://%s:%d%s)r`   rsplitra   )r]   rf   rb   rb   rc   _server_urlp   s    
rj   TViewableFuncOrPathzbool | LocationboolrR   )panel	server_idtitlelocationadmindocc           	   	     s   ddl m} ddlm} tjr@ dtdtdtj	dd  
dttj  ttt   fd	d
} | t X t| ttfr|  } t| |r| || | n|| || |  W  d    S 1 s0    Y  d S )Nr0   )rm   rV   Zdocument_readyze
            const body = document.getElementsByTagName('body')[0]
            body.classList.remove(z, z)
            )codec                   s   t tt  d S N)loggerinfor?   idsession_contextrr   rb   rc   _log_session_destroyed   s    z+_eval_panel.<locals>._log_session_destroyed)Zpanerm   templaterW   r2   global_loading_spinnerZjs_on_eventr   r=   loading_spinnerZon_eventr   rN   Z_schedule_on_loadru   rv   r@   rw   Zon_session_destroyedrM   
isinstancer   r   Z_modify_doc)	rm   rn   ro   rp   rq   rr   Zas_panelrW   r{   rb   rz   rc   _eval_panelv   s"    


r   zCallable[..., None]None)funcr^   c                   s   t jrt jjsJt }|j}t }| r:|| n|	|  dS t
trltjdrljj }ntdd }t j t fdd}|rd|_t j| dS )z
    Wrap async event loop scheduling to ensure that with_lock flag
    is propagated from function to partial wrapping it.
    NlockFc                    s   t  d z$| i |I d H W W  d    S  ty\ } zt| W Y d }~n
d }~0 0 W d    n1 sr0    Y  d S rt   )rM   	ExceptionrN   Z_handle_exception)argskwecurdocr   rb   rc   wrapper   s
    
$zasync_execute.<locals>.wrapperT)rN   r   ry   r*   currentasyncio_loopZ_handle_exception_wrapperZ
is_runningadd_callbackrun_until_completer   r   hasattrr   r   getattrr   ZnolockZadd_next_tick_callback)r   ZioloopZ
event_loopr   Zunlockrb   r   rc   async_execute   s"    
r   z'BokehSessionContext'rx   c                 C  s   ddl m } | j}tjd }|jr&dn|j}|jsF|dksB||v rFd S tjd  d7  < |dkrt||krt| }t	||d  d  }|tjd< t
j  d d d | jjdd	||< tjd
 d S )Nr0   r1   sessionsr   totalr6   z
User-Agent)ZlaunchedstartedrenderedZended
user_agentsession_info)r2   rw   rN   r   _adminsession_historylenlistitemsdictdtdatetimenow	timestamprequestheadersgetparamtrigger)ry   r2   
session_idr   historyZold_historyrb   rb   rc   _initialize_session_info   s$    


r   zBundle | tuple[str, str]zdict[ID, DocJson]zlist[RenderItem]zTemplate | str | Nonezdict[str, Any])bundle	docs_jsonrender_itemsro   r|   template_variablesr^   c                 C  s   |du rt }| \}}t }tt|dd}	t|	d|}	tt||}
| }|t||||	|
 |t	t
d t|dkr|d d |d	< |d	 j|d
< |du rt	}nt|trtd| }||}|S )a  
    Render an HTML page from a template and Bokeh render items.

    Arguments
    ---------
    bundle (tuple):
        A tuple containing (bokehjs, bokehcss)
    docs_json (JSON-like):
        Serialized Bokeh Document
    render_items (RenderItems)
        Specific items to render from the document and where
    title (str or None)
        A title for the HTML page. If None, DEFAULT_TITLE is used
    template (str or Template or None, optional) :
        A Template to be used for the HTML page. If None, FILE is used.
    template_variables (dict, optional):
        Any Additional variables to pass to the template

    Returns
    -------
    str
    NF)quotezapplication/json)ro   bokeh_js	bokeh_cssZplot_scriptdocsbasemacrosr6   r   r   rr   rootsz{% extends base %}
)DEFAULT_TITLEr&   r   r   r   r   copyupdater   rB   r   r   r   r   r\   rH   from_stringrender)r   r   r   ro   r|   r   r   r   Zjson_idjsonscriptcontexthtmlrb   rb   rc   html_page_for_render_items   s4    


r   z'ServerSession'z'Resources'z
str | Nonezstr | TemplatezOptional[Dict[str, Any]])session	resourcesro   tokenr|   r   r^   c              	   C  s   |j dkr&tjr tj dt nt}nt}| j}tj|jd< ||jd< |j	D ]}t
||d qLt|ph| j|j	dd}	|d u ri }|tu rt}t|T t|j	|}
t|
i |	g|||d}tjr|d	d
t dtj d}W d    n1 s0    Y  |S )Nserverrh   Z
theme_namedist_url)r   F)r   r   use_for_title)r|   r   z<body>z<body class="z pn-z">)moderN   rel_pathrF   rC   documentr2   themeZ_template_variablesr   rJ   r   r   r   rB   rM   rI   r   r}   replacer=   r~   )r   r   ro   r   r|   r   r   rr   rootZrender_itemr   r   rb   rb   rc   server_html_page_for_session  s8    




"r   Fc           	   	   C  sR   t j||d}t| j|}t||ddg}|tti |||d tj	||dS )NabsoluteF)r   	elementidr   )app_pathabsolute_url)r   r   )
rG   
from_bokehrI   r   r   addr   r   r   r   )	rr   r   r   
element_idr   r   r   r   r   rb   rb   rc   autoload_js_script?  s
    r   c                      sD   e Zd Z fddZdd fddZdddd	 fd
dZ  ZS )r   c                   s,   t  j|i | d | _tjr(| jtj_d S rt   )super__init___autoreload_stop_eventrN   _admin_context_loopselfr   kwargs	__class__rb   rc   r   L  s    zServer.__init__r   r^   c                   sX   t    tjr | jtjj tjrTddl	m
} t  | _}| jj||| _d S )Nr6   )setup_autoreload_watcher)r   startrN   r   r   r   Zrun_load_hookr2   
autoreloadreloadr   asyncioEventr   r   Zcreate_task_autoreload_task)r   r   Z
stop_eventr   rb   rc   r   R  s    
zServer.startTrl   )waitr^   c                   sD    j r" fdd} jj|  t j|d tjr@tj  d S )Nc                     s    j    jI d H  d S rt   )r   setr   rb   r   rb   rc   stop_autoreload_  s    
z$Server.stop.<locals>.stop_autoreload)r   )	r   r   r   r   r   stoprN   r   Zrun_unload_hook)r   r   r   r   r   rc   r   [  s    zServer.stop)T)__name__
__module____qualname__r   r   r   __classcell__rb   rb   r   rc   r   J  s   	r   c                   @  s   e Zd Zedd ZdS )SessionPrefixHandlerc                 c  s4  | j j| jjd}|ds&|d7 }td|}ddg| jjd	d }t
jt
j }}| jdd d}|d ur|| jjd}tt
 |t
_|t
_W d    n1 s0    Y  z>d V  W tt
 |t
_|t
_W d    n1 s0    Y  n8tt
 |t
_|t
_W d    n1 s$0    Y  0 d S )N rh   r[   bokeh-absolute-urldefault)r   urir   application_context_urlendswithr   joinstripcountrN   base_urlr   get_argumentr3   )r   prefixr   r   old_urlZold_relZabs_urlrb   rb   rc   _session_prefixk  s(    

 
$
&
z$SessionPrefixHandler._session_prefixN)r   r   r   r   r  rb   rb   rb   rc   r   i  s   r   c                   @  s   e Zd ZdZdd ZdS )LoginUrlMixinzi
    Overrides the AuthRequestHandler.get_login_url implementation to
    correctly handle prefixes.
    c                 C  sH   | j jjdur d| j j|  S | j jjdur<d| j jj S tddS )zm Delegates to``get_login_url`` method of the auth provider, or the
        ``login_url`` attribute.

        N.zSlogin_url or get_login_url() must be supplied when authentication hooks are enabled)applicationauth_providerget_login_urlZ	login_urlRuntimeErrorr   rb   rb   rc   r    s
    zLoginUrlMixin.get_login_urlN)r   r   r   __doc__r  rb   rb   rb   rc   r    s   r  c                      sF   e Zd Ze fddZdd ZdddZdd	 Zed
d Z  Z	S )r#   c                   s   ddl m } | jj}d }|jrD|tjv rDtj| | j}tj|}|d u rt 	 I d H }t
|jJ |jr|jpzdd }|tj|< || j}|tj|< |  W d    n1 s0    Y  |S )Nr0   r1   c                 S  s    | j | jddgd dfS )Nr   s   defaultr   zutf-8)path	argumentsr   decoderrb   rb   rc   <lambda>      z(DocHandler.get_session.<locals>.<lambda>)r2   r   r	  Zreuse_sessionsrN   _session_key_funcs	_sessionsr   r   get_sessionrM   r   Zsession_key_funcZblock_expiration)r   r2   r	  r   keykey_funcr   rb   rc   r    s     


&zDocHandler.get_sessionc                   s   | j }|jd u r2|jpg fdd| jjD n|jfdd| jj D }|jd u r~|jpdg fdd| jjD  n|j  fdd| jj D }|rd|v rd|jpg vr|d= | jj	d u ri n| jj	}|||d}|
| jj | j |S )	Nc                   s   g | ]}| vr|qS rb   rb   ).0header)excluded_headersrb   rc   
<listcomp>  s   z6DocHandler._generate_token_payload.<locals>.<listcomp>c                   s   i | ]\}}| v r||qS rb   rb   r  kv)allowed_headersrb   rc   
<dictcomp>  s   z6DocHandler._generate_token_payload.<locals>.<dictcomp>c                   s   g | ]}| vr|qS rb   rb   )r  cookie)excluded_cookiesrb   rc   r    s   c                   s    i | ]\}}| v r||j qS rb   )valuer  )allowed_cookiesrb   rc   r    s   Cookie)r   cookiesr
  )r  Zinclude_headersZexclude_headersr   r   r   Zinclude_cookiesZexclude_cookiesr#  r
  r   r   process_request)r   appr   r#  r
  payloadrb   )r!  r  r  r  rc   _generate_token_payload  s"    



z"DocHandler._generate_token_payloadFc                 C  s   t j}|r|r"|t jjd u r"dS d}t|j}t|dkrHtj	f}n$t|dkrdtj	| j
jf}ntdtj d}zJ|| }t|tr| | W dS |sd	tjd
| j
jd}|rd}W n  ty   dtj d}Y n0 ||fS )z	
        authorize_callback)TNFr6   r0   zAuthorization callback must accept either 1) a single argument which is the user name or 2) two arguments which includes the user name and the url path the user is trying to access.z. is not authorized to access this application.)NNzAccess denied! User z% is not authorized for the given app r  Nz8Authorization callback errored. Could not validate user )r2   r(  Z_param__privatevaluesinspect	signature
parametersr   rN   Z	user_infor   r	  r  userr   r\   redirectr   )r   r   Zauth_cb
authorizedZauth_paramsZ	auth_args
auth_errorrb   rb   rc   
_authorize  s8    



zDocHandler._authorizec                 C  sZ   t jr@tt j}t| }W d    qD1 s40    Y  nt}|jt jddd|dS )NzPanel: Authorization ErrorzAuthorization ErrorzUser is not authorized.)npm_cdnro   Z
error_typeerror	error_msg)	r2   Zauth_templateopenrH   r   readrE   r   r2  )r   r0  fr|   rb   rb   rc   _render_auth_error  s    .zDocHandler._render_auth_errorc              
     s.  |   }tjrt| j| j|dd}t|j |  \}}W d    n1 sN0    Y  |d u rdd S |s| 	|}| 
dd | | d S | j}|  f tj| jjdd }	|	| jtjv }
|  I d H }|
r8tj|	| j|u r8t| jj| jjd}t|j}|| |d= t||j|j|j|d	}n|j}ttt|j t|j t | j! }| jd
d\}}|rt"|||jj#||jj$|jj%d}n0|d u rW d    W d    d S | 	|}W d    n1 s0    Y  W d    n1 s
0    Y  | 
dd | | d S )NF)
initializeContent-Typez	text/htmlc                 S  s   | j S rt   )r	  r  rb   rb   rc   r    r  z DocHandler.get.<locals>.<lambda>)
secret_keysignedZsession_expiry)r;  r<  Z
expirationZextra_payloadT)r   )r   ro   r   r|   r   )&r'  r2   r(  rL   r  r   rM   r   r1  r8  
set_headerwriter  rN   r  r   r	  r  r  r(   r;  Zsign_sessionsr)   r   r   r'   Zsession_token_expirationru   rv   r>   rw   rG   r   r   r   ro   r|   r   )r   r   r   r&  Ztemp_sessionr/  r0  pager%  r  Zold_requestr   r   r   r   rb   rb   rc   r     sd    *





JzDocHandler.get)F)
r   r   r   r.   r  r'  r1  r8  r   r   rb   rb   r   rc   r#     s   
$r#   z/?c                   @  s   e Zd ZdZddddZdS )r"   zD Implements a custom Tornado handler for the autoload JS chunk

    r   r   c           
        s  | j dd d}|s$| jddd d S | j ddd}| j dd d}|rVd	jt|d
}nd }|  x |  I d H }t|j@ tj	| j
|dd}t|j||j|||dd}	W d    n1 s0    Y  W d    n1 s0    Y  | dd | |	 d S )Nzbokeh-autoload-elementr     z)No bokeh-autoload-element query parameter)status_codereasonzbokeh-app-pathrh   r   z{uri.scheme}://{uri.netloc})r   Tr   r:  zapplication/javascript)r   Z
send_errorformatr   r  r  rM   r   rG   r   r  r   r   r   r=  r>  )
r   r   r   r   r   r   Z
server_urlr   r   Zjsrb   rb   rc   r   <  s*    
BzAutoloadJsHandler.getN)r   r   r   r  r   rb   rb   rb   rc   r"   7  s   r"   z/autoload.js   c                      s    e Zd ZdZ fddZ  ZS )r$   z]
    Custom RootHandler that provides the CDN_DIST directory as a
    template variable.
    c                   s   t |d< t j|i |S )NZ	PANEL_CDN)rC   r   r   r   r   rb   rc   r   `  s    zRootHandler.render)r   r   r   r  r   r   rb   rb   r   rc   r$   Z  s   r$   c                 C  sP   |dkrdn|}| }||dkr"dn|d 7 }|j d urF|td|j ifS |ti fS )Nrh   z/__patchedrootz/static/(.*)r	  )Zstatic_pathr-   r%   )r   r  r%  Zrouterb   rb   rc   create_static_handlerh  s    
rE  win32)   r6   Zjupyter_serverZjupyter_clientZpytestc                   @  sb   e Zd ZdZg dZddddddZddd	d
dZeddddddZddddddZ	dS )ComponentResourceHandlera=  
    A handler that serves local resources relative to a Python module.
    The handler resolves a specific Panel component by module reference
    and name, then resolves an attribute on that component to check
    if it contains the requested resource path.

    /<endpoint>/<module>/<class>/<attribute>/<path>
    )Z__css__Z__javascript__Z__js_module__Z__javascript_modules__
_resourcesZ_cssZ_jsZbase_csscssZ_stylesheets	modifiersNOptional[str])r	  default_filenamec                 C  s   || _ || _d S rt   )r   rM  )r   r	  rM  rb   rb   rc   r9    s    z#ComponentResourceHandler.initializer\   )r	  r^   c           
        s  | d}t|dk r tdd|^}}}}zt|}W n tyX   tdddY n0 zt|| W n ty   tdddY n0 || jvrtd	d
zt |}W n ty   tdddY n0 |dkr|d }|dd }||vrtdd|| }d| }n|dkr*dd |	 D }t
|trDt|	 }nt
|ttjfr\|g} fdd|D }d|}	|	|vrtd	d|jstddtt|jj|	 S )zB
        Resolves the resource the URL pattern refers to.
        rh      r@  zMalformed URL  zModule not foundNzComponent not found  z"Requested resource type not valid.zResource type not foundrI  r   r6   z_resources/rK  c                 S  s,   g | ]$}| d g D ]}t|tr|qqS )Zstylesheets)r   r   r\   )r  rsstrb   rb   rc   r    s   
z;ComponentResourceHandler.parse_url_path.<locals>.<listcomp>c                   s*   g | ]"}t t |d dtjjdqS )T)relativerh   )r\   rK   r   osr	  sep)r  resource	componentrb   rc   r    s   z"Requested resource was not listed.z+Requested module does not reference a file.)ra   r   r+   	importlibimport_moduleModuleNotFoundErrorr   AttributeError_resource_attrsr)  r   r   r   r\   pathlibPurePathr   __file__Pathparent)
r   r	  partsmodclsZrtypesubpathmoduler   r   rb   rW  rc   parse_url_path  sT    











z'ComponentResourceHandler.parse_url_path)r   r	  r^   c                 C  s   |S rt   rb   )re  r   r	  rb   rb   rc   get_absolute_path  s    z*ComponentResourceHandler.get_absolute_path)r   absolute_pathr^   c                 C  s2   t j|stdt j|s.tdd| j|S )NrO  rP  z%s is not a file)rT  r	  existsr+   isfile)r   r   rj  rb   rb   rc   validate_absolute_path  s
    z/ComponentResourceHandler.validate_absolute_path)NN)
r   r   r   r  r]  r9  rh  classmethodri  rm  rb   rb   rb   rc   rH    s   	=rH  Tz7TViewableFuncOrPath | Mapping[str, TViewableFuncOrPath]rL  zOptional[str | list[str]]zOptional[IOLoop]zStoppableThread | Server)panelsrf   addresswebsocket_originloopshowr   ro   verboserp   threadedrq   r^   c                 K  s   t td t|fi t|||||||||	|d
}|
r|du rHtddn| |d< }d|vrjt j|d< tt|| f|d}|d }|t	j
|< |  nt| fi |S |S )	a  
    Allows serving one or more panel objects on a single server.
    The panels argument should be either a Panel object or a function
    returning a Panel object or a dictionary of these two. If a
    dictionary is supplied the keys represent the slugs at which
    each app is served, e.g. `serve({'app': panel1, 'app2': panel2})`
    will serve apps at /app and /app2 on the server.

    Reference: https://panel.holoviz.org/user_guide/Server_Configuration.html#serving-multiple-apps

    Arguments
    ---------
    panel: Viewable, function or {str: Viewable or function}
      A Panel object, a function returning a Panel object or a
      dictionary mapping from the URL slug to either.
    port: int (optional, default=0)
      Allows specifying a specific port
    address : str
      The address the server should listen on for HTTP requests.
    websocket_origin: str or list(str) (optional)
      A list of hosts that can connect to the websocket.

      This is typically required when embedding a server app in
      an external web site.

      If None, "localhost" is used.
    loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())
      The tornado IOLoop to run the Server on
    show : boolean (optional, default=True)
      Whether to open the server in a new browser tab on start
    start : boolean(optional, default=True)
      Whether to start the Server
    title: str or {str: str} (optional, default=None)
      An HTML title for the application or a dictionary mapping
      from the URL slug to a customized title
    verbose: boolean (optional, default=True)
      Whether to print the address and port
    location : boolean or panel.io.location.Location
      Whether to create a Location component to observe and
      set the URL location.
    threaded: boolean (default=False)
      Whether to start the server on a new Thread
    admin: boolean (default=False)
      Whether to enable the admin panel
    kwargs: dict
      Additional keyword arguments to pass to Server instance
    T)
rf   rp  rq  rr  rs  r   ro   rt  rp   rq   NF)Zmake_currentrr  rn   )targetio_loopr   r   )r   r   r   r*   uuiduuid4hexStoppableThread
get_serverrN   _threadsr   )ro  rf   rp  rq  rr  rs  r   ro   rt  rp   ru  rq   r   r   rn   rb   rb   rc   serve  s$    @






r~  c                   @  s"   e Zd ZdZdddZdd ZdS )ProxyFallbackHandlerz\A `RequestHandler` that wraps another HTTP server callback and
    proxies the subpath.
    Nc                 C  s   || _ || _d S rt   fallbackproxy)r   r  r  rb   rb   rc   r9  B  s    zProxyFallbackHandler.initializec                 C  s:   | j r| jj| j d| j_| | j d| _|   d S )Nr   T)r  r   r	  r   r  	_finishedZ	on_finishr   rb   rb   rc   prepareF  s
    zProxyFallbackHandler.prepare)N)r   r   r   r  r9  r  rb   rb   rb   rc   r  =  s   
r  c                 C  s   g }|   D ]b\}}|ds&d| }|dkr6tdt|}tj|sVtd| |d| td|if q|dt	 dt
i f |S )zy
    Returns a list of tornado routes of StaticFileHandlers given a
    dictionary of slugs and file paths to serve.
    rh   z/staticzHStatic file route may not use /static this is reserved for internal use.z!Cannot serve non-existent path %sz%s/(.*)r	  z(.*))r   r`   
ValueErrorr4   rT  r	  isdirappendr-   rD   rH  )static_dirspatternsslugr	  rb   rb   rc   get_static_routesN  s     
r  zMapping[str, str]zOptional[bool]zOptional[int]z
bool | str)!rm   rf   rp  rq  rr  rs  r   ro   rt  rp   rq   r  
basic_authoauth_provider	oauth_keyoauth_secretoauth_redirect_urioauth_extra_paramsoauth_error_templatecookie_secretoauth_encryption_keyoauth_jwt_useroauth_refresh_tokensoauth_guest_endpointsoauth_optionallogin_endpointlogout_endpointlogin_templatelogout_templater   livenesswarmr^   c            8   	     sr  ddl m  ddlm}! | dt j}"| dg  | d< }#t| t	ri }$| 
 D ]\}%}&|%dr|%dkstd|%d	t|t	rz||% }'W q ty   td
|% ddY q0 n|}'|%dr|%nd|% }%dtjv rNddlm}( t|&|(rNt|&})|%dkrtd|%ds,|%d7 }%|#d|% d tt	|)|%df qVt|&tjrdt|&}&t|&tr|&drtj|&rt|& |$|%< }&|
|&_qVt|&tr|&|$|%< qVtt t!|&|"|'|	|
}*t"|*|
d|$|%< qVnt| tjrt| } t| trd|&i} nZt| trB| drBtj| rBdt| i}$n&tt t!| |"||	|
}*dt"|*|
di}$|svj#r|$$ D ]}&j#rt%t&|$$  t'|&}+W d   n1 s0    Y  nt'|&}+t(|+j) t*+d W d   n1 s0    Y  t,|+j)dd q~|
rNd|$v r.tdddl-m.}, t|,}-t"|-|$d< |#t/|7 }#|durj|_0j0dkr|!d g d}.|#1|. t*2dt*dg |rt|t3rdn|}/|#d|/ t4t	|$d fg7 }#t	| }0|rt56|j7 ||0d!< n|0d"ddkrt89 |0d!< d#|0vr&t:|0d#< |dur8||0d$< |rXt|t&sP|g}||0d%< ddl m  i }1| d&|} s|rdd'l;m<}2m=}3  r |1d(< |2}4n
|_>|3}4|4||||d)|0d*< |r|_?|r|_@|r|_A|r|_B|r |_C|dur|_D|dur |_E|dur0|_F|dur@|_GjB|0d+< tH|$fd,|i|0|rjIpnd-}d.| d/jJ jK }5tLd0|5  | g ft*jM|"< |1t*jNjO< |rpd1 fd2d3}6jPQ|6 fd4d5}7fd6d7ztRRtRjS|7 W n ty    Y n0 |rnT  zjPT  W n. tUyR   Y n tVyl   tWd8 Y n0 S )9aI  
    Returns a Server instance with this panel attached as the root
    app.

    Arguments
    ---------
    panel: Viewable, function or {str: Viewable}
      A Panel object, a function returning a Panel object or a
      dictionary mapping from the URL slug to either.
    port: int (optional, default=0)
      Allows specifying a specific port
    address : str
      The address the server should listen on for HTTP requests.
    websocket_origin: str or list(str) (optional)
      A list of hosts that can connect to the websocket.

      This is typically required when embedding a server app in
      an external web site.

      If None, "localhost" is used.
    loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())
      The tornado IOLoop to run the Server on.
    show : boolean (optional, default=False)
      Whether to open the server in a new browser tab on start.
    start : boolean(optional, default=False)
      Whether to start the Server.
    title : str or {str: str} (optional, default=None)
      An HTML title for the application or a dictionary mapping
      from the URL slug to a customized title.
    verbose: boolean (optional, default=False)
      Whether to report the address and port.
    location : boolean or panel.io.location.Location
      Whether to create a Location component to observe and
      set the URL location.
    admin: boolean (default=False)
      Whether to enable the admin panel
    static_dirs: dict (optional, default={})
      A dictionary of routes and local paths to serve as static file
      directories on those routes.
    basic_auth: str (optional, default=None)
      Password or filepath to use with basic auth provider.
    oauth_provider: str
      One of the available OAuth providers
    oauth_key: str (optional, default=None)
      The public OAuth identifier
    oauth_secret: str (optional, default=None)
      The client secret for the OAuth provider
    oauth_redirect_uri: Optional[str] = None,
      Overrides the default OAuth redirect URI
    oauth_jwt_user: Optional[str] = None,
      Key that identifies the user in the JWT id_token.
    oauth_extra_params: dict (optional, default={})
      Additional information for the OAuth provider
    oauth_error_template: str (optional, default=None)
      Jinja2 template used when displaying authentication errors.
    cookie_secret: str (optional, default=None)
      A random secret string to sign cookies (required for OAuth)
    oauth_encryption_key: str (optional, default=None)
      A random encryption key used for encrypting OAuth user
      information and access tokens.
    oauth_guest_endpoints: list (optional, default=None)
      List of endpoints that can be accessed as a guest without authenticating.
    oauth_optional: bool (optional, default=None)
      Whether the user will be forced to go through login flow or if
      they can access all applications as a guest.
    oauth_refresh_tokens: bool (optional, default=None)
      Whether to automatically refresh OAuth access tokens when they expire.
    login_endpoint: str (optional, default=None)
      Overrides the default login endpoint `/login`
    logout_endpoint: str (optional, default=None)
      Overrides the default logout endpoint `/logout`
    logout_template: str (optional, default=None)
      Jinja2 template served when viewing the login endpoint when
      authentication is enabled.
    logout_template: str (optional, default=None)
      Jinja2 template served when viewing the logout endpoint when
      authentication is enabled.
    session_history: int (optional, default=None)
      The amount of session history to accumulate. If set to non-zero
      and non-None value will launch a REST endpoint at
      /rest/session_info, which returns information about the session
      history.
    liveness: bool | str (optional, default=False)
      Whether to add a liveness endpoint. If a string is provided
      then this will be used as the endpoint, otherwise the endpoint
      will be hosted at /liveness.
    warm: bool (optional, default=False)
      Whether to run the applications before serving them to ensure
      all imports and caches are fully warmed up before serving the app.
    kwargs: dict
      Additional keyword arguments to pass to Server instance.

    Returns
    -------
    server : panel.io.server.Server
      Bokeh Server instance running this panel
    r0   r1   r6   )REST_PROVIDERSrn   extra_patternsrh   z)Invalid URL: trailing slash '/' used for z not supported.zGKeys of the title dictionary and of the apps dictionary must match. No z# key found in the title dictionary.Nflaskr   )Flaskz'Flask apps must be served on a subpath.^z.*r  )z.pyz.ipynbz.md)rq   T)destroyz/adminzTCannot enable admin panel because another app is being served on the /admin endpoint)admin_panelr   restr   r  z/%s)Zapplicationsrw  Z	num_procsindexrp  Zallow_websocket_originZbasic_login_template)BasicAuthProviderOAuthProviderr  )r  r  r  r  error_templater  r  rf   	localhostzhttp://rg   zLaunching server at z/loginc                     s    js rnd d S )Nrh   )rs  r  rb   )r  r2   r  r   rb   rc   show_callback  s    z!get_server.<locals>.show_callbackc                    s   j   d S rt   )rw  Zadd_callback_from_signalr   r   )do_stopr   rb   rc   sig_exit  s    zget_server.<locals>.sig_exitc                    s    j   d S rt   )rw  r   r  )r   rb   rc   r    s    zget_server.<locals>.do_stopz_IOLoop couldn't be started. Ensure it is started by process invoking the panel.io.server.serve.)Xr2   r  r  poprx  ry  rz  r   r   r   r   r   r  KeyErrorr`   sysmodulesr  r  r/   r  r  r^  ra  r\   rT  r	  rl  r7   r   BkApplicationr   r   r   r   r   r)  rA   r   rL   rM   r   rN   Z_on_loadr8   rq   r  r  r   extendpublishrl   r<   r   Zset_event_loopr   r*   r   
INDEX_HTMLauthr  r  r  r  r  r  r  r  r  r  r  r  r   rp  rf   r   print_serversZ_server_configZ_tornadorw  r   signalSIGINTr   r  	TypeErrorr5   )8rm   rf   rp  rq  rr  rs  r   ro   rt  rp   rq   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r   r  rn   r  Zappsr  r%  Ztitle_r  Zwsgihandlerr   r  Zadmin_handlerpatternZliveness_endpointoptsZserver_configr  r  providerr]   r  r  rb   )r  r2   r  r  r   rc   r|  e  sB    







**













r|  c                      sB   e Zd ZdZdd fddZdddd	Zddd
dZ  ZS )r{  z"Thread class with a stop() method.r*   )rw  c                   s   t  jf i | || _d S rt   )r   r   rw  )r   rw  r   r   rb   rc   r     s    zStoppableThread.__init__r   r   c                 C  s   t | dr"| j| j| j  }}}n| j| j| j  }}}|s@d S d }z`||i |}W t|trz|	  W n t
y~   Y n0 t | dr| `| `| `q| `| `| `nPt|trz|	  W n t
y   Y n0 t | dr| `| `| `n| `| `| `0 d S )N_target)r   r  _args_kwargsZ_Thread__targetZ_Thread__argsZ_Thread__kwargsr   r   r   r   )r   rv  r   r   Zbokeh_serverrb   rb   rc   run  s0    




zStoppableThread.runc                 C  s   | j | j j d S rt   )rw  r   r   r   rb   rb   rc   r     s    zStoppableThread.stop)r   r   r   r  r   r  r   r   rb   rb   r   rc   r{    s   r{  )F)r   NNNTTNTTFF)r  
__future__r   r   r   r   rY  r*  loggingrT  r^  r  r  	threadingrx  
contextlibr   	functoolsr   r   r   r   typesr   r   typingr	   r
   r   r   r   r   r   urllib.parser   r   Zbokehr   ZtornadoZbokeh.applicationr   r  Z#bokeh.application.handlers.functionr   Zbokeh.core.json_encoderr   Zbokeh.core.templatesr   r   r   Zbokeh.core.validationr   Zbokeh.core.validation.warningsr   Zbokeh.embed.bundler   Zbokeh.embed.elementsr   Zbokeh.embed.utilr   Zbokeh.embed.wrappersr   Zbokeh.modelsr   Zbokeh.server.serverr   ZBokehServerZbokeh.server.urlsr    r!   Z&bokeh.server.views.autoload_js_handlerr"   ZBkAutoloadJsHandlerZbokeh.server.views.doc_handlerr#   ZBkDocHandlerZbokeh.server.views.root_handlerr$   ZBkRootHandlerZ!bokeh.server.views.static_handlerr%   Zbokeh.util.serializationr&   Zbokeh.util.tokenr'   r(   r)   Ztornado.ioloopr*   Ztornado.webr+   r,   r-   r.   Ztornado.wsgir/   r2   utilr3   r4   Zutil.warningsr5   r  r7   r   r8   r9   r:   r;   r  r<   Zloadingr=   r>   r?   r@   r   rA   r   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   r   rL   rN   rM   	getLoggerr   ru   Zbokeh.bundlerO   Zbokeh.core.typesrP   Zbokeh.document.documentrQ   rR   Zbokeh.server.contextsrS   Zbokeh.server.sessionrT   Zjinja2rU   Ztemplate.baserW   ZviewablerX   rY   rp   rZ   Z	TViewablePathLiker\   rk   r	  r   dirnamer`  r  r   rd   rj   r   r   ZparameterizedZasync_executorr   Z_on_session_created_internalr  r   r   r   r   r   r  rE  platformversion_infotypeZget_event_loop_policyZWindowsSelectorEventLoopPolicyr  Zset_event_loop_policyZWindowsProactorEventLoopPolicyrH  r~  r  r  r|  Threadr{  rb   rb   rb   rc   <module>   sD  $0
 B.

  !




^           (XP  @