Tyler Houssian
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# FastAPI + Panel The Python library [Panel](https://panel.holoviz.org/index.html) is a high-level app and dashboarding solution for Python. It allows you to create custom interactive web apps and dashboards supporting nearly all plotting libraries. Sometimes though, it is also useful to embed a Panel app in large web applications, such as [FastAPI](https://fastapi.tiangolo.com/). 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 of configuration that we'll show you here below. ## Configuration Following FastAPI's [Tutorial - User Guide](https://fastapi.tiangolo.com/tutorial/) make sure you first have FastAPI installed using: `pip install "fastapi[all]"`. Also make sure Panel is installed `pip install panel`. Next you'll need to create a file called `main.py`. In `main.py` you'll need to import the following( which should all be already available from the above pip installs): ```python import panel as pn from bokeh.embed import server_document from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates ``` 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 `main.py` and set up the path to your templates like so: ```python app = FastAPI() templates = Jinja2Templates(directory="templates") ``` We will now need to create our first rout via an async function and point it to the path of our server: ```python @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}) ``` 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 `templates` and create the file `base.html` in that directory. Now add the following to `base.html`. This is a minimal version but feel free to add whatever else you need to it. ``` <!DOCTYPE html> <html> <head> <title>Panel in FastAPI: sliders</title> </head> <body> {{ script|safe }} </body> </html> ``` Return back to your `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. ```python pn.serve({'/app': createApp}, port=5000, allow_websocket_origin=["127.0.0.1:8000"], address="127.0.0.1", show=False) ``` 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. `conda env config vars set BOKEH_ALLOW_WS_ORIGIN=127.0.0.1:8000` ## Sliders App Based on a standard FastAPI app template, this app shows how to integrate Panel and FastAPI. Create a new directory called panelApps. Inside your new directory, create a new file called `app1.py` and another new file called `pn_app.py`. In `app1.py` add the following code for an example sliders app: ```python 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 ``` Now navigate to `pn_app.py` and add the following code to create server document from an instance of your SineWave class. > Note: here is where createApp is created that is used by `pn.serve()` in `main.py`. ```python import panel as pn from .app1 import SineWave def createApp(): sw = SineWave() return pn.Row(sw.param, sw.plot).servable() ``` We now need to return to our `main.py` and import the createApp function. Add the following import near the other imports: ```python from panelApps.pn_app import createApp ``` Your file structure should now be like the following: ``` fastapi │ main.py │ └───panelApps │ │ app1.py │ │ pn_app.py │ └───templates │ base.html ``` And your finished `main.py` should look like this: ```python import panel as pn from bokeh.embed import server_document from fastapi import FastAPI, Request from fastapi.templating import Jinja2Templates from panelApps.pn_app import createApp app = FastAPI() templates = Jinja2Templates(directory="templates") @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}) pn.serve({'/app': createApp}, port=5000, allow_websocket_origin=["127.0.0.1:8000"], address="127.0.0.1", show=False) ``` ## Get Ready To Start Up 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: ``` uvicorn main:app --reload ``` The output should give you a link to go to to view your app: ``` Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` Go to that address and your app should be there running! ## Multiple Apps This is just a basic single app example. To run multiple apps you will need to do the following: 1. Create a new file in your panelApps directory (ex. `app2.py`) and add your new app code. 2. Create another pn_app file in your panelApps directory (ex. `pn_app2.py`) That might look something like this: ```python import panel as pn from .app2 import SineWave2 def createApp2(doc): sw = SineWave2() return pn.Row(sw.param, sw.plot).servable() ``` 3. Create a new html template (ex. app2.html) with the same contents as base.html 4. Import your new app in main.py `from panelApps.pn_app import createApp2` 5. Add your new app to the dictionary in bk_worker() Server ```python {'/app': createApp, '/app2': createApp2} ``` 7. Add a new async function to rout your new app (The bottom of `main.py` should look something like this now): ```python @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}) pn.serve({'/app': createApp, '/app2': createApp2}, port=5000, allow_websocket_origin=["127.0.0.1:8000"], address="127.0.0.1", show=False) ``` ## Conclusion 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. Visit [https://github.com/t-houssian/FastAPI-Panel](https://github.com/t-houssian/FastAPI-Panel) For all of the code above.

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully