英文:
Dash app: To develop a method that runs every time someone opens the app
问题
我正在创建一个Dash Web应用程序,需要开发一种方法,每当有人打开这个Web应用程序时都可以创建一个新的数据框来绘制。以下是我正在使用的示例代码。
def plot():
dataframe = get_new_data_frame()
fig = px.bar(dataframe, x='date', y='count')
return fig
app.layout = html.Div(children=[
html.H1(children='New DataFrame and Plot Every Time'),
dcc.Graph(id='example-graph', figure=plot())
])
在这里,我想开发一个函数get_new_data_frame()
,它每次有人打开这个Web应用程序时都返回一个新创建的数据框。我应该如何做到这一点?
英文:
I'm creating a dash web-app and need to develop a method to create a new dataframe for plotting every time someone opens this web-app
below are the sample code that I'm using.
def plot():
dataframe = get_new_data_frame()
fig = px.bar(dataframe, x='date', y='count')
return fig
app.layout = html.Div(children=[
html.H1(children='New DataFrame and Plot Every Time'),
dcc.Graph(id='example-graph',
figure = plot())
])
Here I want to develop a function get_new_data_frame() which return a newly created dataframe every time someone opens this web app. How can I do this ?
答案1
得分: 2
你可以通过将一个函数分配给你的应用程序的布局来实现这一点。然后,在这个函数内部创建你的数据框,并将其传递给布局。
默认情况下,Dash 应用程序将 app.layout 存储在内存中。这确保了布局仅在应用程序启动时计算一次。
如果你将 app.layout 设置为一个函数,那么你可以在每次页面加载时提供动态布局。
Dash 提供了以下示例:
import datetime
from dash import html, Dash
app = Dash(__name__)
def serve_layout():
return html.H1('The time is: ' + str(datetime.datetime.now()))
app.layout = serve_layout
if __name__ == '__main__':
app.run_server(debug=True)
应用于你的情况,代码可能如下所示:
def plot():
dataframe = get_new_data_frame()
fig = px.bar(dataframe, x="date", y="count")
return fig
def serve_layout():
return html.Div(
children=[
html.H1(children="New DataFrame and Plot Every Time"),
dcc.Graph(id="example-graph", figure=plot()),
]
)
app.layout = serve_layout
详细内容请参考:https://dash.plotly.com/live-updates
英文:
You can do this by assigning a function to the layout of your app. Then inside this function create your dataframe and pass it to the layout
> By default, Dash apps store the app.layout in memory. This ensures that the layout is only computed once, when the app starts.
>
> If you set app.layout to a function, then you can serve a dynamic layout on every page load.
Dash provides the following example:
import datetime
from dash import html, Dash
app = Dash(__name__)
def serve_layout():
return html.H1('The time is: ' + str(datetime.datetime.now()))
app.layout = serve_layout
if __name__ == '__main__':
app.run_server(debug=True)
https://dash.plotly.com/live-updates
Applied to your case it could look something like this:
def plot():
dataframe = get_new_data_frame()
fig = px.bar(dataframe, x="date", y="count")
return fig
def serve_layout():
return html.Div(
children=[
html.H1(children="New DataFrame and Plot Every Time"),
dcc.Graph(id="example-graph", figure=plot()),
]
)
app.layout = serve_layout
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论