{ "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", "