{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "As the core user guides including the [Introduction](../getting_started/Introduction.ipynb) have demonstrated, it is easy to display Panel apps in the notebook, launch them from an interactive Python prompt, and deploy them as a standalone Bokeh server app from the commandline. However, it is also often useful to embed a Panel app in large web application, such as a FastAPI web server. [FastAPI](https://fastapi.tiangolo.com/) is especially useful compared to others like Flask and Django because of it's lightning fast, lightweight framework. Using Panel with FastAPI requires a bit more work than for notebooks and Bokeh servers.\n", "\n", "Following FastAPI's [Tutorial - User Guide](https://fastapi.tiangolo.com/tutorial/) make sure you first have FastAPI installed using: `conda install -c conda-forge fastapi`. Also make sure Panel is installed `conda install -c conda-forge panel`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configuration\n", "\n", "Before we start adding a bokeh app to our FastApi server we have to set up some of the basic plumbing. In the `examples/apps/fastApi` folder we will add some basic configurations.\n", "\n", "You'll need to create a file called `examples/apps/fastApi/main.py`.\n", "\n", "In `main.py` you'll need to import the following( which should all be already available from the above conda installs):\n", "\n", "```python\n", "import panel as pn\n", "from bokeh.embed import server_document\n", "from fastapi import FastAPI, Request\n", "from fastapi.templating import Jinja2Templates\n", "```\n", "\n", "\n", "Each of these will be explained as we add them in.\n", "\n", "Next we are going to need to create an instance of FastAPI below your imports in `main.py` and set up the path to your templates like so:\n", "\n", "\n", "```python\n", "app = FastAPI()\n", "templates = Jinja2Templates(directory=\"examples/apps/fastApi/templates\")\n", "```\n", "\n", "We will now need to create our first rout via an async function and point it to the path of our server:\n", "\n", "```python\n", "@app.get(\"/\")\n", "async def bkapp_page(request: Request):\n", " script = server_document('http://127.0.0.1:5000/app')\n", " return templates.TemplateResponse(\"base.html\", {\"request\": request, \"script\": script})\n", "```\n", "\n", "As you can see in this code we will also need to create an html [Jinja2](https://fastapi.tiangolo.com/advanced/templates/#using-jinja2templates) template. Create a new directory named `examples/apps/fastApi/templates` and create the file `examples/apps/fastApi/templates/base.html` in that directory.\n", "\n", "Now add the following to `base.html`. This is a minimal version but feel free to add whatever else you need to it.\n", "\n", "```html\n", "\n", "\n", " \n", " Panel in FastAPI: sliders\n", " \n", " \n", " {{ script|safe }}\n", " \n", "\n", "```\n", "\n", "Return back to your `examples/apps/fastApi/main.py` file. We will use pn.serve() to start the bokeh server (Which Panel is built on). Configure it to whatever port and address you want, for our example we will use port 5000 and address 127.0.0.1. show=False will make it so the bokeh server is spun up but not shown yet. The allow_websocket_origin will list of hosts that can connect to the websocket, for us this is fastApi so we will use (127.0.0.1:8000). The `createApp` function call in this example is how we call our panel app. This is not set up yet but will be in the next section.\n", "\n", "```python\n", "pn.serve({'/app': createApp},\n", " port=5000, allow_websocket_origin=[\"127.0.0.1:8000\"],\n", " address=\"127.0.0.1\", show=False)\n", "```\n", "\n", "You could optionally add BOKEH_ALLOW_WS_ORIGIN=127.0.0.1:8000 as an environment variable instead of setting it here. In conda it is done like this.\n", "\n", "`conda env config vars set BOKEH_ALLOW_WS_ORIGIN=127.0.0.1:8000`\n", "\n", "## Sliders app\n", "\n", "Based on a standard FastAPI app template, this app shows how to integrate Panel and FastAPI.\n", "\n", "The sliders app is in `examples/apps/fastApi/sliders`. We will cover the following additions/modifications to the Django2 app template:\n", "\n", " * `sliders/sinewave.py`: a parameterized object (representing your pre-existing code)\n", "\n", " * `sliders/pn_app.py`: creates an app function from the SineWave class" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![screenshot of sliders app](../_static/sliders.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To start with, in `sliders/sinewave.py` we create a parameterized object to serve as a placeholder for your own, existing code:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import param\n", "from bokeh.models import ColumnDataSource\n", "from bokeh.plotting import figure\n", "\n", "\n", "class SineWave(param.Parameterized):\n", " offset = param.Number(default=0.0, bounds=(-5.0, 5.0))\n", " amplitude = param.Number(default=1.0, bounds=(-5.0, 5.0))\n", " phase = param.Number(default=0.0, bounds=(0.0, 2 * np.pi))\n", " frequency = param.Number(default=1.0, bounds=(0.1, 5.1))\n", " N = param.Integer(default=200, bounds=(0, None))\n", " x_range = param.Range(default=(0, 4 * np.pi), bounds=(0, 4 * np.pi))\n", " y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10))\n", "\n", " def __init__(self, **params):\n", " super(SineWave, self).__init__(**params)\n", " x, y = self.sine()\n", " self.cds = ColumnDataSource(data=dict(x=x, y=y))\n", " self.plot = figure(plot_height=400, plot_width=400,\n", " tools=\"crosshair, pan, reset, save, wheel_zoom\",\n", " x_range=self.x_range, y_range=self.y_range)\n", " self.plot.line('x', 'y', source=self.cds, line_width=3, line_alpha=0.6)\n", "\n", " @param.depends('N', 'frequency', 'amplitude', 'offset', 'phase', 'x_range', 'y_range', watch=True)\n", " def update_plot(self):\n", " x, y = self.sine()\n", " self.cds.data = dict(x=x, y=y)\n", " self.plot.x_range.start, self.plot.x_range.end = self.x_range\n", " self.plot.y_range.start, self.plot.y_range.end = self.y_range\n", "\n", " def sine(self):\n", " x = np.linspace(0, 4 * np.pi, self.N)\n", " y = self.amplitude * np.sin(self.frequency * x + self.phase) + self.offset\n", " return x, y\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However the app itself is defined we need to configure an entry point, which is a function that adds the application to it. In case of the slider app it looks like this in `sliders/pn_app.py`:\n", "\n", "```python\n", "import panel as pn\n", "\n", "from .sinewave import SineWave\n", "\n", "def createApp():\n", " sw = SineWave()\n", " return pn.Row(sw.param, sw.plot).servable()\n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We now need to return to our `main.py` and import the createApp function. Add the following import near the other imports:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "from sliders.pn_app import createApp\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Your file structure should now be like the following:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "fastApi\n", "│ main.py\n", "│\n", "└───sliders\n", "│ │ sinewave.py\n", "│ │ pn_app.py\n", "│\n", "└───templates\n", " │ base.html\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And your finished `main.py` should look like this:\n", "\n", "```python\n", "import panel as pn\n", "from bokeh.embed import server_document\n", "from fastapi import FastAPI, Request\n", "from fastapi.templating import Jinja2Templates\n", "\n", "from sliders.pn_app import createApp\n", "\n", "app = FastAPI()\n", "templates = Jinja2Templates(directory=\"templates\")\n", "\n", "@app.get(\"/\")\n", "async def bkapp_page(request: Request):\n", " script = server_document('http://127.0.0.1:5000/app')\n", " return templates.TemplateResponse(\"base.html\", {\"request\": request, \"script\": script})\n", "\n", "\n", "pn.serve({'/app': createApp},\n", " port=5000, allow_websocket_origin=[\"127.0.0.1:8000\"],\n", " address=\"127.0.0.1\", show=False)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "uvicorn main:app --reload\n", "```\n", "\n", "The output should give you a link to go to to view your app:\n", "\n", "```\n", "Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n", "```\n", "\n", "Go to that address and your app should be there running!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiple apps\n", "\n", "\n", "This is the most basic configuration for a bokeh server. It is of course possible to add multiple apps in the same way and then registering them with FastApi in the way described in the [configuration](#Configuration) section above. To see a multi-app fastApi server have a look at ``examples/apps/fastApi_multi_apps`` and launch it with `uvicorn main:app --reload` as before.\n", "\n", "To run multiple apps you will need to do the following:\n", "1. Create a new directory in your and a new file with your panel app (ex. `sinewave2.py`).\n", "2. Create another pn_app file in your new directory (ex. `pn_app2.py`) That might look something like this:\n", "```\n", "import panel as pn\n", "\n", "from .sinewave import SineWave2\n", "\n", "def createApp2():\n", " sw = SineWave()\n", " return pn.Row(sw.param, sw.plot).servable()\n", "```\n", "\n", "With this as your new file structure:\n", "\n", "```\n", "fastApi\n", "│ main.py\n", "│\n", "└───sliders\n", "│ │ sinewave.py\n", "│ │ pn_app.py\n", "│ │\n", "└───sliders2\n", "│ │ sinewave2.py\n", "│ │ pn_app.py\n", "│\n", "└───templates\n", " │ base.html\n", "```\n", "\n", "3. Create a new html template (ex. app2.html) with the same contents as base.html in `examples/apps/fastApi/templates`\n", "4. Import your new app in main.py `from sliders2.pn_app import createApp2`\n", "5. Add your new app to the dictionary in pn.serve()\n", "\n", "```python\n", "{'/app': createApp, '/app2': createApp2}\n", "```\n", "\n", "7. Add a new async function to rout your new app (The bottom of `main.py` should look something like this now):\n", "\n", "```python\n", "@app.get(\"/\")\n", "async def bkapp_page(request: Request):\n", " script = server_document('http://127.0.0.1:5000/app')\n", " return templates.TemplateResponse(\"base.html\", {\"request\": request, \"script\": script})\n", " \n", "@app.get(\"/app2\")\n", "async def bkapp_page2(request: Request):\n", " script = server_document('http://127.0.0.1:5000/app2')\n", " return templates.TemplateResponse(\"app2.html\", {\"request\": request, \"script\": script})\n", "\n", "pn.serve({'/app': createApp, '/app2': createApp2},\n", " port=5000, allow_websocket_origin=[\"127.0.0.1:8000\"],\n", " address=\"127.0.0.1\", show=False)\n", "```\n", "\n", "With this as your file structure\n", "\n", "```\n", "fastApi\n", "│ main.py\n", "│\n", "└───sliders\n", "│ │ sinewave.py\n", "│ │ pn_app.py\n", "│ │\n", "└───sliders2\n", "│ │ sinewave2.py\n", "│ │ pn_app.py\n", "│\n", "└───templates\n", " │ base.html\n", " │ app2.html \n", "```\n", "\n", "Sliders 2 will be available at `http://127.0.0.1:8000/app2`\n", "\n", "## Conclusion\n", "That's it! You now have embedded panel in FastAPI! You can now build off of this to create your own web app tailored to your needs." ] } ], "metadata": { "language_info": { "name": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 4 }