使用主要功能运行破折号应用程序

问题描述 投票:0回答:1

我有一个破折号应用程序(.py),其运行代码看起来像,

# whatever.py

from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd

app = Dash()

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")
app.layout = html.Div(children=[
    html.H1(children='Hello Global Apps'),
    html.Div(children='''
        Dash: A web application framework for your data.
    '''),
    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])
if __name__ == "__main__":
    app.run_server(debug=True)

我使用

HOST=<xxxx> PORT=<xxxx> python -m whatever

执行此操作

我想从 .py 文件中删除 if 段,同时仍然运行提供流量的 dash 服务器

if __name__ == "__main__":
    app.run_server(debug=True)

有什么办法可以实现这一点吗?我愿意编写另一个Python包装文件,或者通过命令行执行任何东西。

请注意:我对whatever.py 不灵活,除了抽象出两条线段之外,无法对其进行任何更改。

抽象出想到的 if 段的一个选项是将此段动态附加到 .py 文件中。我们可以在通过命令行执行期间执行此操作,但这似乎不太稳定或可靠。

python python-3.x plotly-dash
1个回答
0
投票

一种方法是创建一个新的 Python 脚本,仅用于运行服务器,名为

runner.py
。在此文件中,您必须从 dash 应用程序文件导入
app
对象(由于您尚未提供 dash 应用程序的文件名,出于演示目的,我假设它是
dash_application.py
)。

runner.py

from dash_application import app
app.run_server(debug=True)

现在您可以从破折号应用程序文件中删除

if __name__ == "__main__":
段,并通过命令行运行您的应用程序:

$ python3 runner.py
© www.soinside.com 2019 - 2024. All rights reserved.