Logo

The Data Daily

FastAPI — Panel v0.14.0

FastAPI — Panel v0.14.0

Panel generally runs on the Bokeh server which itself runs on Tornado. However, it is also often useful to embed a Panel app in large web application, such as a FastAPI web server. FastAPI 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.

Following FastAPI’s Tutorial - User Guide make sure you first have FastAPI installed using: . Also make sure Panel is installed .

Before we start adding a bokeh app to our FastApi server we have to set up some of the basic plumbing. In the folder we will add some basic configurations. In you’ll need to import the following( which should all be already available from the above conda installs): Each of these will be explained as we add them in. Next we are going to need to create an instance of FastAPI below your imports in and set up the path to your templates like so: We will now need to create our first rout via an async function and point it to the path of our server: As you can see in this code we will also need to create an html Jinja2 template. Create a new directory named and create the file in that directory. Now add the following to . This is a minimal version but feel free to add whatever else you need to it. Return back to your 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 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. 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.

Based on a standard FastAPI app template, this app shows how to integrate Panel and FastAPI. The sliders app is in . We will cover the following additions/modifications to the Django2 app template: : creates an app function from the SineWave class To start with, in we create a parameterized object to serve as a placeholder for your own, existing code: 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 : We now need to return to our and import the createApp function. Add the following import near the other imports: Your file structure should now be like the following: And your finished should look like this: The output should give you a link to go to to view your app: Go to that address and your app should be there running!

Images Powered by Shutterstock