如何在 Dash 应用程序中打印新行

how do I print on new line in Dash application

我创建了一个 dash 应用程序,我必须在其中打印数据库中的最新值。检索数据时,它以元组列表的形式出现,因此我必须对其进行格式化以打印由新行分隔的数据。我现在无法通过我的代码实现它。所以任何建议都会有很大帮助。提前致谢。

以下是流程

我以元组列表的形式接收数据 [(2.27085, 2.73255,1.0),(2.27085, 2.73255,2.0),(2.27085, 2.73255,3.0)] 我有元组中每个值的标签 ['value1', 'value2', 'SNO']

我正在将它们组合起来制作一本字典,结果会是这样的 "{'value1': 2.27085, 'value2': 2.73255, 'SNO': 1.0}

然后我将字典转换为字符串以从中删除 {}。

然后我通过在每个字符串的末尾添加一个新行和一个时间戳将所有字符串连接在一起,所以当我在应用程序上打印时它应该看起来像这样

21:40:41

'value1': 2.27085, 'value2': 2.73255, 'SNO': 1.0

'value1': 2.27085, 'value2': 2.73255, 'SNO': 2.0

'value1': 2.27085, 'value2': 2.73255, 'SNO': 3.0

相反,我在我的 dash 应用程序上得到了这个

21:51:12
'value1': 2.27085, 'value2': 2.73255, 'SNO': 1.0Br(None)'value1': 2.27085, 'value2': 2.73255, 'SNO': 2.0Br(None)'value1': 2.27085, 'value2': 2.73255, 'SNO': 3.0Br(None)

这是我试过的代码

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

printing = html.P(['CONSOLE', html.Br()])

app.layout = html.Div([
    html.Div([
        dcc.Interval(id="interval", interval=0.9 * 1000, n_intervals=0),
        html.Div(id="content"),
    ])
])


def flask_logger():
    log_mssg = ''
    values = [(2.27085, 2.73255, 1.0), (2.27085, 2.73255, 2.0), (2.27085, 2.73255, 3.0)]
    col_name_list = ['value1', 'value2', 'SNO']
    current_time = datetime.datetime.now().strftime('%H:%M:%S')
    if (values is not None and len(values) != 0) and (col_name_list is not None and len(col_name_list) != 0):
        for i in values:
            #concatenate the strings together with a new line at the end
            log_mssg = log_mssg+str(dict(zip(col_name_list, i)))+str(html.Br())
            log_mssg = log_mssg.replace('{', '')
            log_mssg = log_mssg.replace('}', '')
        current_time = [current_time] + [html.Br()] + [log_mssg]
        #print(current_time)
        return current_time
    return 'none'


@app.callback(
    Output("content", "children"),
    Input("interval", "n_intervals"),
    State("content", "children"),
)
def update_output(interval, content):
    if not content:
        return ['']
    x = flask_logger()
    return content + x + [html.Br()]


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

仅供参考,我删除了数据库部分并添加了一些数据来模拟操作,因此任何人都可以直接 运行 代码。

每当我想 return 一个 iterable,每个项目都在单独的行上时,我使用 html.P()。因此,您可以重写 flask_logger 函数以使用:

...
    if (values is not None and len(values) != 0) and (col_name_list is not None and len(col_name_list) != 0):
        log_mssg = [html.P(log_mssg + str(dict(zip(col_name_list, i))).replace('{', '').replace('}', '')) for i in values]
        current_time = [html.P(current_time)] + log_mssg
...