破折号python加载,然后稍后更新

时间:2018-12-12 12:53:07

标签: python pandas plotly-dash

我对破折号和python还是有些陌生,所以请原谅我,让我知道是否有可以简化或需要更改的内容。

问题

我想在文本中显示一个数字,并每10分钟更新一次。我已经成功完成了此操作,但是问题是我希望它立即加载,然后每十分钟更新一次……但是,当应用程序首次启动时,要花10分钟才能加载此文本。

我觉得我需要为回调添加一个while / if逻辑,但是我不确定。这是指向result

的链接

请参见下面的代码

如果您希望它具有可复制性,则可以在get_data()内的data变量中设置任何数字

#Imports for dash
import dash
from dash.dependencies import Output, Event
import dash_core_components as dcc
import dash_html_components as html

#imports for database connection and data processing
from sshtunnel import SSHTunnelForwarder
import pymysql as db
import pandas as pd


# ssh variables go here
host = 
localhost = 
ssh_username = 
private_key = 
# database variables go here
user=
password=
database=

#This is the function for processing a query
def query(q):

    #function for getting data from database

def get_data():
    df_test = query('call example') #calls a procedure which returns a number
    data = df_test['test'].loc[0] # selects the result from the dataframe
    data_insert = 'This month we have {} new clients!!!'.format(data) #inserts the result into the string
    return data_insert

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.Div(id='my-div', children='''
        '''.format(get_data())),
        dcc.Interval(
            id='update',
            interval=10* 60000 # I would like for this to be 10 minutes
        )
    ]
)
@app.callback(Output('my-div', 'children'),
              events=[Event('update', 'interval')])
def update_data(): # function for returning the new data
    return get_data()

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

1 个答案:

答案 0 :(得分:0)

Dash community通过很好的解决方案回到了我的身边。见下文:

from datetime import datetime

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output


def serve_layout():
    return html.Div(
        [dcc.Interval(id="interval", interval=10000), html.P(id="output")]
    )


app = dash.Dash()

app.layout = serve_layout


@app.callback(Output("output", "children"), [Input("interval", "n_intervals")])
def display_time(n):
    return datetime.now().strftime("The time is: %H:%M:%S")


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