{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import panel as pn\n",
    "pn.extension()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One of the main design goals for Panel was that it should make it possible to seamlessly transition back and forth between interactively prototyping a dashboard in the notebook or on the commandline to deploying it as a standalone server app. This section shows how to display panels interactively, embed static output, save a snapshot, and deploy as a separate web-server app. For more information about deploying Panel apps to various cloud providers see the [Server Deployment](Server_Deployment.ipynb) documentation.\n",
    "\n",
    "## Configuring output\n",
    "\n",
    "As you may have noticed, almost all the Panel documentation is written using notebooks. Panel objects display themselves automatically in a notebook and take advantage of Jupyter Comms to support communication between the rendered app and the Jupyter kernel that backs it on the Python end. To display a Panel object in the notebook is as simple as putting it on the end of a cell. Note, however, that the ``panel.extension`` first has to be loaded to initialize the required JavaScript in the notebook context.  Also, if you are working in JupyterLab, the pyviz labextension has to be installed with:\n",
    "\n",
    "    jupyter labextension install @pyviz/jupyterlab_pyviz\n",
    "\n",
    "### Optional dependencies\n",
    "\n",
    "Also remember that in order to use certain components such as Vega, LaTeX, and Plotly plots in a notebook, the models must be loaded using the extension. If you forget to load the extension, you should get a warning reminding you to do it. To load certain JS components, simply list them as part of the call to ``pn.extension``:\n",
    "\n",
    "    pn.extension('vega', 'katex')\n",
    "\n",
    "Here we've ensured that the Vega and LaTeX JS dependencies will be loaded.\n",
    "\n",
    "### Initializing JS and CSS \n",
    "\n",
    "Additionally, any external ``css_files``, ``js_files`` and ``raw_css`` needed should be declared in the extension. The ``js_files`` should be declared as a dictionary mapping from the exported JS module name to the URL containing the JS components, while the ``css_files`` can be defined as a list:\n",
    "\n",
    "    pn.extension(js_files={'deck': https://unpkg.com/deck.gl@~5.2.0/deckgl.min.js},\n",
    "                 css_files=['https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css'])\n",
    "\n",
    "The ``raw_css`` argument allows defining a list of strings containing CSS to publish as part of the notebook and app.\n",
    "\n",
    "Providing keyword arguments via the ``extension`` is the same as setting them on ``pn.config``, which is the preferred approach outside the notebook. ``js_files`` and ``css_files`` may be set to your chosen values as follows:\n",
    "\n",
    "    pn.config.js_files  = {'deck': 'https://unpkg.com/deck.gl@~5.2.0/deckgl.min.js'}\n",
    "    pn.config.css_files = ['https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Display in the notebook\n",
    "\n",
    "#### The repr\n",
    "    \n",
    "Once the extension is loaded, Panel objects will display themselves if placed at the end of cell in the notebook:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pane = pn.panel('<marquee>Here is some custom HTML</marquee>')\n",
    "\n",
    "pane"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To instead see a textual representation of the component, you can use the ``pprint`` method on any Panel object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pane.pprint()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The ``display`` function\n",
    "\n",
    "To avoid having to put a Panel on the last line of a notebook cell, e.g. to display it from inside a function call, you can use the IPython built-in ``display`` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def display_marquee(text):\n",
    "    display(pn.panel('<marquee>{text}</marquee>'.format(text=text)))\n",
    "    \n",
    "display_marquee('This Panel was displayed from within a function')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Inline apps\n",
    "\n",
    "Lastly it is also possible to display a Panel object as a Bokeh server app inside the notebook.  To do so call the ``.app`` method on the Panel object and provide the URL of your notebook server:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pane.app('localhost:8888')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The app will now run on a Bokeh server instance separate from the Jupyter notebook kernel, allowing you to quickly test that all the functionality of your app works both in a notebook and in a server context."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ipywidgets\n",
    "\n",
    "If the `jupyter_bokeh` package is installed it is also possible to render Panel objects as an ipywidget rather than using Bokeh's internal communication mechanisms.  You can enable ipywidgets support  globally using:\n",
    "\n",
    "```python\n",
    "pn.extension(comms='ipywidgets')\n",
    "# or\n",
    "pn.config.comms = 'ipywidgets'\n",
    "```\n",
    "\n",
    "This global setting can be useful when trying to serve an entire notebook using [Voilà](https://github.com/voila-dashboards/voila). Alternatively, we can convert individual objects to an ipywidget one at a time using the `pn.ipywidget()` function:\n",
    "\n",
    "```python\n",
    "ipywidget = pn.ipywidget(pane)\n",
    "ipywidget\n",
    "```\n",
    "\n",
    "This approach also allows combining a Panel object with any other Jupyter-widget--based model:\n",
    "\n",
    "```python\n",
    "from ipywidgets import Accordion\n",
    "Accordion(children=[pn.ipywidget(pane)])\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To use Panel's ipywidgets support in JupyterLab, the following extensions have to be installed:\n",
    "    \n",
    "```\n",
    "jupyter labextension install @jupyter-widgets/jupyterlab-manager\n",
    "jupyter labextension install @bokeh/jupyter_bokeh\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally the `jupyter_bokeh` package should be installed using either pip:\n",
    "\n",
    "```\n",
    "pip install jupyter_bokeh\n",
    "```\n",
    "\n",
    "or using conda:\n",
    "\n",
    "```\n",
    "conda install -c bokeh jupyter_bokeh\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Display in the Python REPL\n",
    "\n",
    "Working from the command line will not automatically display rich representations inline as in a notebook, but you can still interact with your Panel components if you start a Bokeh server instance and open a separate browser window using the ``show`` method. The method has the following arguments:\n",
    "\n",
    "    port: int (optional)\n",
    "       Allows specifying a specific port (default=0 chooses an arbitrary open port)\n",
    "    websocket_origin: str or list(str) (optional)\n",
    "       A list of hosts that can connect to the websocket.\n",
    "       This is typically required when embedding a server app in\n",
    "       an external-facing web site.\n",
    "       If None, \"localhost\" is used.\n",
    "    threaded: boolean (optional, default=False)\n",
    "       Whether to launch the Server on a separate thread, allowing\n",
    "       interactive use.\n",
    "    title : str\n",
    "       A string title to give the Document (if served as an app)\n",
    "    **kwargs : dict\n",
    "       Additional keyword arguments passed to the bokeh.server.server.Server instance.\n",
    "\n",
    "To work with an app completely interactively you can set ``threaded=True`` which will launch the server on a separate thread and let you interactively play with the app.\n",
    "\n",
    "<img src='https://assets.holoviews.org/panel/gifs/commandline_show.gif'></img>\n",
    "\n",
    "The ``.show`` call will return either a Bokeh server instance (if ``threaded=False``) or a ``StoppableThread`` instance (if ``threaded=True``) which both provide a ``stop`` method to stop the server instance."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Serving multiple apps\n",
    "\n",
    "If you want to serve more than one app on a single server you can use the ``pn.serve`` function. By supplying a dictionary where the keys represent the URL slugs and the values must be either Panel objects or functions returning Panel objects you can easily launch a server with a number of apps, e.g.:\n",
    "\n",
    "```python\n",
    "pn.serve({'markdown': '# This is a Panel app', 'json': pn.pane.JSON({'abc': 123})})\n",
    "```\n",
    "\n",
    "The ``pn.serve`` function accepts the same arguments as the `show` method."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "## Launching a server on the commandline\n",
    "\n",
    "Once the app is ready for deployment it can be served using the Bokeh server.  For a detailed breakdown of the design and functionality of Bokeh server, see the [Bokeh documentation](https://bokeh.pydata.org/en/latest/docs/user_guide/server.html). The most important thing to know is that Panel (and Bokeh) provide a CLI command to serve a Python script, app directory, or Jupyter notebook containing a Bokeh or Panel app. To launch a server using the CLI, simply run:\n",
    "\n",
    "    panel serve app.ipynb\n",
    "    \n",
    "Alternatively you can also list multiple apps:\n",
    "\n",
    "    panel serve app1.py app2.ipynb\n",
    "    \n",
    "or even serve a number of apps at once:\n",
    "\n",
    "    panel serve apps/*.py\n",
    "    \n",
    "The ``panel serve`` command has the following options:\n",
    "\n",
    "    positional arguments:\n",
    "      DIRECTORY-OR-SCRIPT   The app directories or scripts or notebooks to serve \n",
    "                            (serve empty document if not specified)\n",
    "\n",
    "    optional arguments:\n",
    "      -h, --help            show this help message and exit\n",
    "      --port PORT           Port to listen on\n",
    "      --address ADDRESS     Address to listen on\n",
    "      --log-level LOG-LEVEL\n",
    "                            One of: trace, debug, info, warning, error or critical\n",
    "      --log-format LOG-FORMAT\n",
    "                            A standard Python logging format string (default:\n",
    "                            '%(asctime)s %(message)s')\n",
    "      --log-file LOG-FILE   A filename to write logs to, or None to write to the\n",
    "                            standard stream (default: None)\n",
    "      --args ...            Any command line arguments remaining are passed on to\n",
    "                            the application handler\n",
    "      --show                Open server app(s) in a browser\n",
    "      --allow-websocket-origin HOST[:PORT]\n",
    "                            Public hostnames which may connect to the Bokeh\n",
    "                            websocket\n",
    "      --prefix PREFIX       URL prefix for Bokeh server URLs\n",
    "      --keep-alive MILLISECONDS\n",
    "                            How often to send a keep-alive ping to clients, 0 to\n",
    "                            disable.\n",
    "      --check-unused-sessions MILLISECONDS\n",
    "                            How often to check for unused sessions\n",
    "      --unused-session-lifetime MILLISECONDS\n",
    "                            How long unused sessions last\n",
    "      --stats-log-frequency MILLISECONDS\n",
    "                            How often to log stats\n",
    "      --mem-log-frequency MILLISECONDS\n",
    "                            How often to log memory usage information\n",
    "      --use-xheaders        Prefer X-headers for IP/protocol information\n",
    "      --session-ids MODE    One of: unsigned, signed, or external-signed\n",
    "      --index INDEX         Path to a template to use for the site index\n",
    "      --disable-index       Do not use the default index on the root path\n",
    "      --disable-index-redirect\n",
    "                            Do not redirect to running app from root path\n",
    "      --num-procs N         Number of worker processes for an app. Using 0 will\n",
    "                            autodetect number of cores (defaults to 1)\n",
    "      --websocket-max-message-size BYTES\n",
    "                            Set the Tornado websocket_max_message_size value\n",
    "                            (defaults to 20MB) NOTE: This setting has effect ONLY\n",
    "                            for Tornado>=4.5\n",
    "      --dev [FILES-TO-WATCH [FILES-TO-WATCH ...]]\n",
    "                            Enable live reloading during app development.By\n",
    "                            default it watches all *.py *.html *.css *.yaml\n",
    "                            filesin the app directory tree. Additional files can\n",
    "                            be passedas arguments. NOTE: This setting only works\n",
    "                            with a single app.It also restricts the number of\n",
    "                            processes to 1.\n",
    "\n",
    "To turn a notebook into a deployable app simply append ``.servable()`` to one or more Panel objects, which will add the app to Bokeh's ``curdoc``, ensuring it can be discovered by Bokeh server on deployment. In this way it is trivial to build dashboards that can be used interactively in a notebook and then seamlessly deployed on Bokeh server.\n",
    "\n",
    "When called on a notebook, `panel serve` first converts it to a python script using [`nbconvert.PythonExporter()`](https://nbconvert.readthedocs.io/en/stable/api/exporters.html), albeit with [IPython magics](https://ipython.readthedocs.io/en/stable/interactive/magics.html) stripped out. This means that non-code cells, such as raw cells, are entirely handled by `nbconvert` and [may modify the served app](https://nbsphinx.readthedocs.io/en/latest/raw-cells.html).\n",
    "\n",
    "### Accessing session state\n",
    "\n",
    "Whenever a Panel app is being served the ``panel.state`` object exposes some of the internal Bokeh server components to a user.\n",
    "\n",
    "#### Document\n",
    "\n",
    "The current Bokeh ``Document`` can be accessed using ``panel.state.curdoc``.\n",
    "\n",
    "#### Request arguments\n",
    "\n",
    "When a browser makes a request to a Bokeh server a session is created for the Panel application. The request arguments are made available to be accessed on ``pn.state.session_args``. For example if your application is hosted at ``localhost:8001/app``, appending ``?phase=0.5`` to the URL will allow you to access the phase variable using the following code:\n",
    "\n",
    "```python\n",
    "try:\n",
    "    phase = int(pn.state.session_args.get('phase')[0])\n",
    "except Exception:\n",
    "    phase = 1\n",
    "```\n",
    "\n",
    "This mechanism may be used to modify the behavior of an app dependending on parameters provided in the URL. \n",
    "\n",
    "### Accessing the Bokeh model\n",
    "\n",
    "Since Panel is built on top of Bokeh, all Panel objects can easily be converted to a Bokeh model. The ``get_root`` method returns a model representing the contents of a Panel:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = pn.Column('# Some markdown').get_root()\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default this model will be associated with Bokeh's ``curdoc()``, so if you want to associate the model with some other ``Document`` ensure you supply it explictly as the first argument. Once you have access to the underlying bokeh model you can use all the usual bokeh utilities such as ``components``, ``file_html``, or ``show``"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bokeh.embed import components, file_html\n",
    "from bokeh.io import show\n",
    "\n",
    "script, html = components(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Embedding\n",
    "\n",
    "Panel generally relies on either the Jupyter kernel or a Bokeh Server to be running in the background to provide interactive behavior. However for simple apps with a limited amount of state it is also possible to `embed` all the widget state, allowing the app to be used entirely from within Javascript. To demonstrate this we will create a simple app which simply takes a slider value, multiplies it by 5 and then display the result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "slider = pn.widgets.IntSlider(start=0, end=10)\n",
    "\n",
    "@pn.depends(slider.param.value)\n",
    "def callback(value):\n",
    "    return '%d * 5 = %d' % (value, value*5)\n",
    "\n",
    "row = pn.Row(slider, callback)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we displayed this the normal way it would call back into Python every time the value changed. However, the `.embed()` method will record the state of the app for the different widget configurations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "row.embed()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you try the widget above you will note that it only has 3 different states, 0, 5 and 10. This is because by default embed will try to limit the number of options of non-discrete or semi-discrete widgets to at most three values. This can be controlled using the `max_opts` argument to the embed method. The full set of options for the embed method include:\n",
    "\n",
    "- **max_states**: The maximum number of states to embed\n",
    "\n",
    "- **max_opts**: The maximum number of states for a single widget\n",
    "\n",
    "- **json** (default=True): Whether to export the data to json files\n",
    "\n",
    "- **save_path** (default='./'): The path to save json files to\n",
    "\n",
    "- **load_path** (default=None):  The path or URL the json files will be loaded from (same as ``save_path`` if not specified)\n",
    "\n",
    "As you might imagine if there are multiple widgets there can quickly be a combinatorial explosion of states so by default the output is limited to about 1000 states. For larger apps the states can also be exported to json files, e.g. if you want to serve the app on a website specify the ``save_path`` to declare where it will be stored and the ``load_path`` to declare where the JS code running on the website will look for the files."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Saving \n",
    "\n",
    "In case you don't need an actual server or simply want to export a static snapshot of a panel app, you can use the ``save`` method, which allows exporting the app to a standalone HTML or PNG file.\n",
    "\n",
    "By default, the HTML file generated will depend on loading JavaScript code for BokehJS from the online ``CDN`` repository, to reduce the file size. If you need to work in an airgapped or no-network environment, you can declare that ``INLINE`` resources should be used instead of ``CDN``:\n",
    "\n",
    "```python\n",
    "from bokeh.resources import INLINE\n",
    "panel.save('test.html', resources=INLINE)\n",
    "```\n",
    "\n",
    "Additionally the save method also allows enabling the `embed` option, which, as explained above, will embed the apps state in the app or save the state to json files which you can ship alongside the exported HTML.\n",
    "\n",
    "Finally, if a 'png' file extension is specified, the exported plot will be rendered as a PNG, which currently requires Selenium and PhantomJS to be installed:\n",
    "\n",
    "```python\n",
    "pane.save('test.png')\n",
    "\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
