From 1351e7fd7b560b7bd32f0f601ab614f3a1e47715 Mon Sep 17 00:00:00 2001 From: Tyler Houssian Date: Tue, 2 Nov 2021 06:30:59 -0600 Subject: [PATCH] Added FastApi in the user guide for embedding apps (#2870) --- examples/apps/fastApi/main.py | 40 ++ examples/apps/fastApi/sliders/pn_app.py | 8 + examples/apps/fastApi/sliders/sinewave.py | 35 ++ examples/apps/fastApi/templates/base.html | 9 + examples/apps/fastApi_multi_apps/main.py | 45 ++ .../apps/fastApi_multi_apps/sliders/pn_app.py | 8 + .../fastApi_multi_apps/sliders/sinewave.py | 35 ++ .../fastApi_multi_apps/sliders2/pn_app.py | 8 + .../fastApi_multi_apps/sliders2/sinewave.py | 35 ++ .../fastApi_multi_apps/templates/app2.html | 9 + .../fastApi_multi_apps/templates/base.html | 9 + examples/user_guide/Django_Apps.ipynb | 15 +- examples/user_guide/FastApi_Apps.ipynb | 435 ++++++++++++++++++ 13 files changed, 690 insertions(+), 1 deletion(-) create mode 100644 examples/apps/fastApi/main.py create mode 100644 examples/apps/fastApi/sliders/pn_app.py create mode 100644 examples/apps/fastApi/sliders/sinewave.py create mode 100644 examples/apps/fastApi/templates/base.html create mode 100644 examples/apps/fastApi_multi_apps/main.py create mode 100644 examples/apps/fastApi_multi_apps/sliders/pn_app.py create mode 100644 examples/apps/fastApi_multi_apps/sliders/sinewave.py create mode 100644 examples/apps/fastApi_multi_apps/sliders2/pn_app.py create mode 100644 examples/apps/fastApi_multi_apps/sliders2/sinewave.py create mode 100644 examples/apps/fastApi_multi_apps/templates/app2.html create mode 100644 examples/apps/fastApi_multi_apps/templates/base.html create mode 100644 examples/user_guide/FastApi_Apps.ipynb diff --git a/examples/apps/fastApi/main.py b/examples/apps/fastApi/main.py new file mode 100644 index 0000000000..025184c45c --- /dev/null +++ b/examples/apps/fastApi/main.py @@ -0,0 +1,40 @@ +from bokeh.embed import server_document +from panel.io.server import Server +from fastapi import FastAPI, Request +from fastapi.templating import Jinja2Templates +from starlette.middleware.cors import CORSMiddleware +from starlette.middleware import Middleware +from threading import Thread +from tornado.ioloop import IOLoop + +from sliders.pn_app import createApp + +app = FastAPI() +templates = Jinja2Templates(directory="templates") + +app.add_middleware( # Middleware to serve panel apps asynchronously via starlette + CORSMiddleware, + allow_origins=['*'], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +@app.get("/") +async def bkapp_page(request: Request): + script = server_document('http://127.0.0.1:5000/app') + return templates.TemplateResponse("base.html", {"request": request, "script": script}) + + +def bk_worker(): + server = Server({'/app': createApp}, + port=5000, io_loop=IOLoop(), + allow_websocket_origin=["*"]) + + server.start() + server.io_loop.start() + +th = Thread(target=bk_worker) +th.daemon = True +th.start() \ No newline at end of file diff --git a/examples/apps/fastApi/sliders/pn_app.py b/examples/apps/fastApi/sliders/pn_app.py new file mode 100644 index 0000000000..6b0b74391e --- /dev/null +++ b/examples/apps/fastApi/sliders/pn_app.py @@ -0,0 +1,8 @@ +import panel as pn + +from .sinewave import SineWave + +def createApp(doc): + sw = SineWave() + row = pn.Row(sw.param, sw.plot) + row.server_doc(doc) \ No newline at end of file diff --git a/examples/apps/fastApi/sliders/sinewave.py b/examples/apps/fastApi/sliders/sinewave.py new file mode 100644 index 0000000000..984e5b7b97 --- /dev/null +++ b/examples/apps/fastApi/sliders/sinewave.py @@ -0,0 +1,35 @@ +import numpy as np +import param +from bokeh.models import ColumnDataSource +from bokeh.plotting import figure + + +class SineWave(param.Parameterized): + offset = param.Number(default=0.0, bounds=(-5.0, 5.0)) + amplitude = param.Number(default=1.0, bounds=(-5.0, 5.0)) + phase = param.Number(default=0.0, bounds=(0.0, 2 * np.pi)) + frequency = param.Number(default=1.0, bounds=(0.1, 5.1)) + N = param.Integer(default=200, bounds=(0, None)) + x_range = param.Range(default=(0, 4 * np.pi), bounds=(0, 4 * np.pi)) + y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10)) + + def __init__(self, **params): + super(SineWave, self).__init__(**params) + x, y = self.sine() + self.cds = ColumnDataSource(data=dict(x=x, y=y)) + self.plot = figure(plot_height=400, plot_width=400, + tools="crosshair, pan, reset, save, wheel_zoom", + x_range=self.x_range, y_range=self.y_range) + self.plot.line('x', 'y', source=self.cds, line_width=3, line_alpha=0.6) + + @param.depends('N', 'frequency', 'amplitude', 'offset', 'phase', 'x_range', 'y_range', watch=True) + def update_plot(self): + x, y = self.sine() + self.cds.data = dict(x=x, y=y) + self.plot.x_range.start, self.plot.x_range.end = self.x_range + self.plot.y_range.start, self.plot.y_range.end = self.y_range + + def sine(self): + x = np.linspace(0, 4 * np.pi, self.N) + y = self.amplitude * np.sin(self.frequency * x + self.phase) + self.offset + return x, y \ No newline at end of file diff --git a/examples/apps/fastApi/templates/base.html b/examples/apps/fastApi/templates/base.html new file mode 100644 index 0000000000..618af12a67 --- /dev/null +++ b/examples/apps/fastApi/templates/base.html @@ -0,0 +1,9 @@ + + + + Panel in FastAPI: sliders + + + {{ script|safe }} + + \ No newline at end of file diff --git a/examples/apps/fastApi_multi_apps/main.py b/examples/apps/fastApi_multi_apps/main.py new file mode 100644 index 0000000000..59e00e7a58 --- /dev/null +++ b/examples/apps/fastApi_multi_apps/main.py @@ -0,0 +1,45 @@ +from bokeh.embed import server_document +from panel.io.server import Server +from fastapi import FastAPI, Request +from fastapi.templating import Jinja2Templates +from starlette.middleware.cors import CORSMiddleware +from starlette.middleware import Middleware +from threading import Thread +from tornado.ioloop import IOLoop + +from sliders.pn_app import createApp +from sliders2.pn_app import createApp2 + +app = FastAPI() +templates = Jinja2Templates(directory="templates") + +app.add_middleware( # Middleware to serve panel apps asynchronously via starlette + CORSMiddleware, + allow_origins=['*'], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +@app.get("/") +async def bkapp_page(request: Request): + script = server_document('http://127.0.0.1:5000/app') + return templates.TemplateResponse("base.html", {"request": request, "script": script}) + +@app.get("/app2") +async def bkapp_page2(request: Request): + script = server_document('http://127.0.0.1:5000/app2') + return templates.TemplateResponse("app2.html", {"request": request, "script": script}) + +def bk_worker(): + server = Server({'/app': createApp, '/app2': createApp2}, + port=5000, io_loop=IOLoop(), + allow_websocket_origin=["*"]) + + server.start() + server.io_loop.start() + +th = Thread(target=bk_worker) +th.daemon = True +th.start() \ No newline at end of file diff --git a/examples/apps/fastApi_multi_apps/sliders/pn_app.py b/examples/apps/fastApi_multi_apps/sliders/pn_app.py new file mode 100644 index 0000000000..6b0b74391e --- /dev/null +++ b/examples/apps/fastApi_multi_apps/sliders/pn_app.py @@ -0,0 +1,8 @@ +import panel as pn + +from .sinewave import SineWave + +def createApp(doc): + sw = SineWave() + row = pn.Row(sw.param, sw.plot) + row.server_doc(doc) \ No newline at end of file diff --git a/examples/apps/fastApi_multi_apps/sliders/sinewave.py b/examples/apps/fastApi_multi_apps/sliders/sinewave.py new file mode 100644 index 0000000000..984e5b7b97 --- /dev/null +++ b/examples/apps/fastApi_multi_apps/sliders/sinewave.py @@ -0,0 +1,35 @@ +import numpy as np +import param +from bokeh.models import ColumnDataSource +from bokeh.plotting import figure + + +class SineWave(param.Parameterized): + offset = param.Number(default=0.0, bounds=(-5.0, 5.0)) + amplitude = param.Number(default=1.0, bounds=(-5.0, 5.0)) + phase = param.Number(default=0.0, bounds=(0.0, 2 * np.pi)) + frequency = param.Number(default=1.0, bounds=(0.1, 5.1)) + N = param.Integer(default=200, bounds=(0, None)) + x_range = param.Range(default=(0, 4 * np.pi), bounds=(0, 4 * np.pi)) + y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10)) + + def __init__(self, **params): + super(SineWave, self).__init__(**params) + x, y = self.sine() + self.cds = ColumnDataSource(data=dict(x=x, y=y)) + self.plot = figure(plot_height=400, plot_width=400, + tools="crosshair, pan, reset, save, wheel_zoom", + x_range=self.x_range, y_range=self.y_range) + self.plot.line('x', 'y', source=self.cds, line_width=3, line_alpha=0.6) + + @param.depends('N', 'frequency', 'amplitude', 'offset', 'phase', 'x_range', 'y_range', watch=True) + def update_plot(self): + x, y = self.sine() + self.cds.data = dict(x=x, y=y) + self.plot.x_range.start, self.plot.x_range.end = self.x_range + self.plot.y_range.start, self.plot.y_range.end = self.y_range + + def sine(self): + x = np.linspace(0, 4 * np.pi, self.N) + y = self.amplitude * np.sin(self.frequency * x + self.phase) + self.offset + return x, y \ No newline at end of file diff --git a/examples/apps/fastApi_multi_apps/sliders2/pn_app.py b/examples/apps/fastApi_multi_apps/sliders2/pn_app.py new file mode 100644 index 0000000000..1c3d79d440 --- /dev/null +++ b/examples/apps/fastApi_multi_apps/sliders2/pn_app.py @@ -0,0 +1,8 @@ +import panel as pn + +from .sinewave import SineWave + +def createApp2(doc): + sw = SineWave() + row = pn.Row(sw.param, sw.plot) + row.server_doc(doc) \ No newline at end of file diff --git a/examples/apps/fastApi_multi_apps/sliders2/sinewave.py b/examples/apps/fastApi_multi_apps/sliders2/sinewave.py new file mode 100644 index 0000000000..984e5b7b97 --- /dev/null +++ b/examples/apps/fastApi_multi_apps/sliders2/sinewave.py @@ -0,0 +1,35 @@ +import numpy as np +import param +from bokeh.models import ColumnDataSource +from bokeh.plotting import figure + + +class SineWave(param.Parameterized): + offset = param.Number(default=0.0, bounds=(-5.0, 5.0)) + amplitude = param.Number(default=1.0, bounds=(-5.0, 5.0)) + phase = param.Number(default=0.0, bounds=(0.0, 2 * np.pi)) + frequency = param.Number(default=1.0, bounds=(0.1, 5.1)) + N = param.Integer(default=200, bounds=(0, None)) + x_range = param.Range(default=(0, 4 * np.pi), bounds=(0, 4 * np.pi)) + y_range = param.Range(default=(-2.5, 2.5), bounds=(-10, 10)) + + def __init__(self, **params): + super(SineWave, self).__init__(**params) + x, y = self.sine() + self.cds = ColumnDataSource(data=dict(x=x, y=y)) + self.plot = figure(plot_height=400, plot_width=400, + tools="crosshair, pan, reset, save, wheel_zoom", + x_range=self.x_range, y_range=self.y_range) + self.plot.line('x', 'y', source=self.cds, line_width=3, line_alpha=0.6) + + @param.depends('N', 'frequency', 'amplitude', 'offset', 'phase', 'x_range', 'y_range', watch=True) + def update_plot(self): + x, y = self.sine() + self.cds.data = dict(x=x, y=y) + self.plot.x_range.start, self.plot.x_range.end = self.x_range + self.plot.y_range.start, self.plot.y_range.end = self.y_range + + def sine(self): + x = np.linspace(0, 4 * np.pi, self.N) + y = self.amplitude * np.sin(self.frequency * x + self.phase) + self.offset + return x, y \ No newline at end of file diff --git a/examples/apps/fastApi_multi_apps/templates/app2.html b/examples/apps/fastApi_multi_apps/templates/app2.html new file mode 100644 index 0000000000..618af12a67 --- /dev/null +++ b/examples/apps/fastApi_multi_apps/templates/app2.html @@ -0,0 +1,9 @@ + + + + Panel in FastAPI: sliders + + + {{ script|safe }} + + \ No newline at end of file diff --git a/examples/apps/fastApi_multi_apps/templates/base.html b/examples/apps/fastApi_multi_apps/templates/base.html new file mode 100644 index 0000000000..618af12a67 --- /dev/null +++ b/examples/apps/fastApi_multi_apps/templates/base.html @@ -0,0 +1,9 @@ + + + + Panel in FastAPI: sliders + + + {{ script|safe }} + + \ No newline at end of file diff --git a/examples/user_guide/Django_Apps.ipynb b/examples/user_guide/Django_Apps.ipynb index fee066d0b3..e01b6b6c7c 100644 --- a/examples/user_guide/Django_Apps.ipynb +++ b/examples/user_guide/Django_Apps.ipynb @@ -293,9 +293,22 @@ } ], "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", "name": "python", - "pygments_lexer": "ipython3" + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.3" } }, "nbformat": 4, diff --git a/examples/user_guide/FastApi_Apps.ipynb b/examples/user_guide/FastApi_Apps.ipynb new file mode 100644 index 0000000000..85ba43adcb --- /dev/null +++ b/examples/user_guide/FastApi_Apps.ipynb @@ -0,0 +1,435 @@ +{ + "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", + "from bokeh.embed import server_document\n", + "from panel.io.server import Server\n", + "from fastapi import FastAPI, Request\n", + "from fastapi.templating import Jinja2Templates\n", + "from starlette.middleware.cors import CORSMiddleware\n", + "from starlette.middleware import Middleware\n", + "from threading import Thread\n", + "from tornado.ioloop import IOLoop\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", + "Next, we are going to need to set up our middleware which will allow Panel to communicate with FastAPI. We will use starlette for this (Which FastAPI is built on). Add the following to your `main.py`:\n", + "\n", + "```python\n", + "\n", + "app.add_middleware(\n", + " CORSMiddleware,\n", + " allow_origins=['*'],\n", + " allow_credentials=True,\n", + " allow_methods=[\"*\"],\n", + " allow_headers=[\"*\"],\n", + ")\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 now need to add the function bk_worker() to start the bokeh server (Which Panel is built on). Configure it to whatever port you want, for our example we will use port 5000. This also uses a [tornado Iloop](https://www.tornadoweb.org/en/stable/ioloop.html). 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", + "def bk_worker():\n", + " server = Server({'/app': createApp},\n", + " port=5000, io_loop=IOLoop(), \n", + " allow_websocket_origin=[\"*\"])\n", + "\n", + " server.start()\n", + " server.io_loop.start()\n", + "```\n", + "\n", + "We now will need to create a thread to call this function. Add the following code to your `examples/apps/fastApi/main.py`.\n", + "\n", + "```python\n", + "th = Thread(target=bk_worker)\n", + "th.daemon = True\n", + "th.start()\n", + "```\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 accepts a bokeh Document and 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(doc):\n", + " sw = SineWave()\n", + " row = pn.Row(sw.param, sw.plot)\n", + " row.server_doc(doc)\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", + "from bokeh.embed import server_document\n", + "from panel.io.server import Server\n", + "from fastapi import FastAPI, Request\n", + "from fastapi.templating import Jinja2Templates\n", + "from starlette.middleware.cors import CORSMiddleware\n", + "from starlette.middleware import Middleware\n", + "from threading import Thread\n", + "from tornado.ioloop import IOLoop\n", + "\n", + "from sliders.pn_app import createApp\n", + "\n", + "app = FastAPI()\n", + "templates = Jinja2Templates(directory=\"templates\")\n", + "\n", + "app.add_middleware( # Middleware to serve panel apps asynchronously via starlette\n", + " CORSMiddleware,\n", + " allow_origins=['*'],\n", + " allow_credentials=True,\n", + " allow_methods=[\"*\"],\n", + " allow_headers=[\"*\"],\n", + ")\n", + "\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", + "def bk_worker():\n", + " server = Server({'/app': createApp},\n", + " port=5000, io_loop=IOLoop(), \n", + " allow_websocket_origin=[\"*\"])\n", + "\n", + " server.start()\n", + " server.io_loop.start()\n", + "\n", + "th = Thread(target=bk_worker)\n", + "th.daemon = True\n", + "th.start()\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You now will need to set an environment variable in order to determine which origins will be allowed to access your bokeh server. Add the following variable to your environment:\n", + "\n", + "```\n", + "BOKEH_ALLOW_WS_ORIGIN=127.0.0.1:8000\n", + "```\n", + "\n", + "This is for the default local host. You may need to change this to whatever your local host is.\n", + "\n", + "If using a conda environment you can create this variable with the following command:\n", + "\n", + "```\n", + "conda env config vars set BOKEH_ALLOW_WS_ORIGIN=127.0.0.1:8000\n", + "```\n", + "\n", + "Your app should be ready to run now. To run your newly created app. Type the following command or copy and paste into your terminal:\n", + "\n", + "```\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(doc):\n", + " sw = SineWave2()\n", + " row = pn.Row(sw.param, sw.plot)\n", + " return row.server_doc(doc)\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 bk_worker() Server\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", + "def bk_worker():\n", + " server = Server({'/app': createApp, '/app2': createApp2},\n", + " port=5000, io_loop=IOLoop(), \n", + " allow_websocket_origin=[\"*\"])\n", + "\n", + " server.start()\n", + " server.io_loop.start()\n", + "\n", + "th = Thread(target=bk_worker)\n", + "th.daemon = True\n", + "th.start()\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": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}