U
    /e*                     @  s$  d Z ddlmZ ddlZeeZddlZddlm	Z	m
Z
mZmZ ddlmZ ddlmZmZmZmZmZ ddlmZ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# ddl$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+ erddl,m-Z- ddl.m/Z/ dZ0G dd de#Z1dS )a    Provide a Bokeh Application Handler to build up documents by running
the code from ``main.py`` or ``main.ipynb`` files in specified directories.

The directory may also optionally contain:

* A ``server_lifecyle.py`` module to provide lifecycle callbacks for the
  application and sessions.

* A ``static`` subdirectory containing app-specific static resources to
  serve.

* A ``theme.yaml`` file containing a Bokeh theme to automatically apply to
  all new documents.

* A ``templates`` subdirectory containing templates for app display

A full directory layout might look like:

.. code-block:: none

    myapp
       |
       +---main.py
       +---server_lifecycle.py
       +---static
       +---theme.yaml
       +---templates
            +---index.html

    )annotationsN)basenamedirnameexistsjoin)
ModuleType)TYPE_CHECKINGAny	CoroutineDictList)EnvironmentFileSystemLoaderTemplate   )PathLike)Document   )ServerContextSessionContext   )
CodeRunner)Handler)NotebookHandler)ScriptHandler)ServerLifecycleHandler)ServerRequestHandler)HTTPServerRequestTheme)DirectoryHandlerc                      s   e Zd ZU dZded< ded< ded< ded< d	ed
< ded< ded< g ddddd fddZeddddZeddddZeddddZ	eddddZ
d dd!d"d#Zd$dd%d&d'Zd$dd%d(d)Zd*d+d,d-d.Zd*d+d,d/d0Zd1d2d3d4d5Zddd6d7Z  ZS )8r    zV Load an application directory which modifies a Document.

    .. autoclasstoc::

    zCodeRunner | None_package_runnerzModuleType | None_packager   _lifecycle_handler_request_handlerzTheme | None_themez
str | None_staticzTemplate | None	_template)argvr   z	List[str]None)filenamer(   returnc                  s>  t    |}t|d}t|rbtt| ||| _| j | _	| j	dk	sPt
| j	tj| j	j< nd| _d| _	t|d}t|d}t|rt|rtd| d |}n*t|r|}nt|r|}ntd| || _|| _|drtnt}|| j|| j	d	| _d}	t|d
}
t|d}t|
r<t|r<tdnt|rL|}	nt|
rZ|
}	|	dk	rxt|	|| j	d	| _nt | _t|
r|	dk	st
t|	|| j	d	| _nt | _d| _t|d}t|rddlm} ||d| _t|d}t|r || _d| _ t|dd}t|r:t!t"t#|d}|$d| _ dS )z
        Keywords:
            filename (str) : a path to an application directory with either "main.py" or "main.ipynb"

            argv (list[str], optional) : a list of string arguments to make available as sys.argv to main.py
        z__init__.pyNzmain.pyz
main.ipynbz)Found both 'main.py' and 'main.ipynb' in z, using 'main.py'z No 'main.py' or 'main.ipynb' in z.ipynb)r*   r(   packagezapp_hooks.pyzserver_lifecycle.pyzVDirectory style apps can provide either server_lifecycle.py or app_hooks.py, not both.z
theme.yamlr   r   )r*   ZstaticZ	templatesz
index.html)loader)%super__init__r   r   r   openreadr!   Z
new_moduler"   AssertionErrorsysmodules__name__logwarning
ValueError_path_mainendswithr   r   _main_handlerr   r#   r   r   r$   r%   Zbokeh.themesr   r&   r'   r   r   r   Zget_template)selfr*   r(   Zsrc_pathZinit_pyZmain_pyZmain_ipymainhandlerhooksZ	app_hooksZ	lifecycleZ	themeyamlr   Z	appstaticZappindexenv	__class__ H/tmp/pip-unpacked-wheel-f5fndrjf/bokeh/application/handlers/directory.pyr/   w   sj    















zDirectoryHandler.__init__)r+   c                 C  s   | j jp| jjS )zE If the handler fails, may contain a related error message.

        )r<   errorr#   r=   rD   rD   rE   rF      s    zDirectoryHandler.errorc                 C  s   | j jp| jjS )zJ If the handler fails, may contain a traceback or other details.

        )r<   error_detailr#   rG   rD   rD   rE   rH      s    zDirectoryHandler.error_detailboolc                 C  s   | j jp| jjS )z; ``True`` if the handler failed to modify the doc

        )r<   failedr#   rG   rD   rD   rE   rJ      s    zDirectoryHandler.failedc                 C  s   | j jS )z Whether it is still safe for the Bokeh server to fork new workers.

        ``False`` if the configured code (script, notebook, etc.) has already
        been run.

        )r<   safe_to_forkrG   rD   rD   rE   rK      s    zDirectoryHandler.safe_to_forkr   )docr+   c                 C  s@   | j jrdS | jdk	r| j|_| jdk	r0| j|_| j| dS )a   Execute the configured ``main.py`` or ``main.ipynb`` to modify the
        document.

        This method will also search the app directory for any theme or
        template files, and automatically configure the document with them
        if they are found.

        N)r#   rJ   r%   Zthemer'   templater<   modify_document)r=   rL   rD   rD   rE   rN      s    	

z DirectoryHandler.modify_documentr   )server_contextr+   c                 C  s&   | j r| jr| j | j | j|S )z Execute `on_server_unloaded`` from ``server_lifecycle.py`` (if
        it is defined) when the server is first started.

        Args:
            server_context (ServerContext) :

        )r!   r"   runr#   on_server_loadedr=   rO   rD   rD   rE   rQ      s    	z!DirectoryHandler.on_server_loadedc                 C  s   | j |S )am   Execute ``on_server_unloaded`` from ``server_lifecycle.py`` (if
        it is defined) when the server cleanly exits. (Before stopping the
        server's ``IOLoop``.)

        Args:
            server_context (ServerContext) :

        .. warning::
            In practice this code may not run, since servers are often killed
            by a signal.


        )r#   on_server_unloadedrR   rD   rD   rE   rS     s    z#DirectoryHandler.on_server_unloadedr   zCoroutine[Any, Any, None])session_contextr+   c                 C  s   | j |S )z Execute ``on_session_created`` from ``server_lifecycle.py`` (if
        it is defined) when a new session is created.

        Args:
            session_context (SessionContext) :

        )r#   on_session_createdr=   rT   rD   rD   rE   rU     s    z#DirectoryHandler.on_session_createdc                 C  s   | j |S )z Execute ``on_session_destroyed`` from ``server_lifecycle.py`` (if
        it is defined) when a session is destroyed.

        Args:
            session_context (SessionContext) :

        )r#   on_session_destroyedrV   rD   rD   rE   rW   "  s    z%DirectoryHandler.on_session_destroyedr   zDict[str, Any])requestr+   c                 C  s   | j |S )a#   Processes incoming HTTP request returning a dictionary of
        additional data to add to the session_context.

        Args:
            request: HTTP request

        Returns:
            A dictionary of JSON serializable data to be included on
            the session context.
        )r$   process_request)r=   rX   rD   rD   rE   rY   ,  s    z DirectoryHandler.process_requestc                 C  s   | j r
dS dt| j S dS )zd The last path component for the basename of the path to the
        configured directory.

        N/)rJ   r   r9   rG   rD   rD   rE   url_path9  s    zDirectoryHandler.url_path)r5   
__module____qualname____doc____annotations__r/   propertyrF   rH   rJ   rK   rN   rQ   rS   rU   rW   rY   r[   __classcell__rD   rD   rB   rE   r    f   s0   
M

r    )2r^   
__future__r   logging	getLoggerr5   r6   r3   os.pathr   r   r   r   typesr   typingr   r	   r
   r   r   Zjinja2r   r   r   Z
core.typesr   documentr   Zapplicationr   r   Zcode_runnerr   r?   r   Znotebookr   scriptr   Zserver_lifecycler   Zserver_request_handlerr   Ztornado.httputilr   Zthemesr   __all__r    rD   rD   rD   rE   <module>   s,   "
	