fastapi+dash

Just a Demo

Ref: https://github.com/rusnyder/fastapi-plotly-dash

# dashapp.py
import os
from pathlib import Path

import dash
import flask
import pandas as pd
from dash import dcc, html
from dash.dependencies import Input, Output


def create_dash_app(requests_pathname_prefix: str | None = None) -> dash.Dash:
    """
    Sample Dash application from Plotly: https://github.com/plotly/dash-hello-world/blob/master/app.py
    """
    server = flask.Flask(__name__)
    server.secret_key = os.environ.get("secret_key", "secret")

    csv = (
        "https://raw.githubusercontent.com/plotly/datasets/master/hello-world-stock.csv"
    )
    if (p := Path(Path(csv).name)).exists():
        csv = p
    df = pd.read_csv(csv)

    app = dash.Dash(
        __name__, server=server, requests_pathname_prefix=requests_pathname_prefix
    )

    app.scripts.config.serve_locally = False
    url = "https://cdn.plot.ly/plotly-basic-latest.min.js"
    if Path("." + (_u := "/static/" + Path(url).name)).exists():
        url = _u
    dcc._js_dist[0]["external_url"] = url

    app.layout = html.Div(
        [
            html.H1("Stock Tickers"),
            dcc.Dropdown(
                id="my-dropdown",
                options=[
                    {"label": "Tesla", "value": "TSLA"},
                    {"label": "Apple", "value": "AAPL"},
                    {"label": "Coke", "value": "COKE"},
                ],
                value="TSLA",
            ),
            dcc.Graph(id="my-graph"),
        ],
        className="container",
    )

    @app.callback(Output("my-graph", "figure"), [Input("my-dropdown", "value")])
    def update_graph(selected_dropdown_value):
        dff = df[df["Stock"] == selected_dropdown_value]
        return {
            "data": [
                {"x": dff.Date, "y": dff.Close, "line": {"width": 3, "shape": "spline"}}
            ],
            "layout": {"margin": {"l": 30, "r": 20, "b": 30, "t": 20}},
        }

    return app

- main.py

#!/usr/bin/env python
import sys
from pathlib import Path

import dash
import pandas as pd
import requests
import uvicorn
from dash import html
from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
from fastapi.responses import RedirectResponse
from fastapi_cdn_host import patch_docs

from dashapp import create_dash_app

app = FastAPI()
patch_docs(app)


@app.get("/")
async def root():
    return {
        "routes": [
            {"method": "GET", "path": "/", "summary": "Landing"},
            {"method": "GET", "path": "/status", "summary": "App status"},
            {
                "method": "GET",
                "path": "/dash",
                "summary": "Sub-mounted Dash application",
            },
            {
                "method": "GET",
                "path": "/dashboard",
                "summary": "Sub-mounted Dash application",
            },
        ]
    }


@app.get("/status")
def get_status():
    return {"status": "ok"}


def generate_table(dataframe, max_rows=10):
    return html.Table(
        [
            html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])),
            html.Tbody(
                [
                    html.Tr(
                        [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]
                    )
                    for i in range(min(len(dataframe), max_rows))
                ]
            ),
        ]
    )


def my_layout():
    url = "https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv"
    if not (p := Path(Path(url).name)).exists():
        p.write_bytes(requests.get(url, verify=False).content)
    df = pd.read_csv(p)
    return html.Div(
        [html.H4(children="US Agriculture Exports (2011)"), generate_table(df)]
    )


dash_app = dash.Dash(__name__, requests_pathname_prefix="/dashboard/")
dash_app.layout = my_layout()


@dash_app.server.route("/")
def index():
    return dash_app.serve_layout()


@dash_app.server.route("/plots")
def plots():
    return dash_app.serve_layout()


# 将 Plotly.dash 应用程序挂载到 FastAPI 应用程序上
app.mount("/dashboard", WSGIMiddleware(dash_app.server))


# A bit odd, but the only way I've been able to get prefixing of the Dash app
# to work is by allowing the Dash/Flask app to prefix itself, then mounting
# it to root
@app.get("/dash/_dash-component-suites/plotly/package_data/plotly.min.js")
def min_js():
    return RedirectResponse("/static/plotly.min.js")


dash_app = create_dash_app(requests_pathname_prefix="/dash/")
app.mount("/dash", WSGIMiddleware(dash_app.server))


def runserver() -> None:
    port = int(a1) if sys.argv[1:] and (a1 := sys.argv[1]).isdigit() else 8000
    uvicorn.run("main:app", reload=True, port=port)


if __name__ == "__main__":
    runserver()

运行:python main.py

效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值