首页 > 解决方案 > DASH - 在函数外获取数据帧(df)

问题描述

我对我的代码有疑问。我想共犯的事情是我上传了一个 *.db 文件并将该文件放入数据框中。之后我想对数据框做一些事情,但我无法在函数之外获取 df!

在第一个函数 (def parse_contents) 中,数据帧 (df) 是通过查询生成的。如果我把 print(df) 放在那里,我会看到 df 填充了来自数据库文件的信息。

然后我返回df(返回df),但我不能在函数之外的df!如果我将 print(df) 放在函数之外,则会收到错误“NameError: name 'df' is not defined”</p>

有没有人可以帮助在其他函数中从 df 获取信息?全局函数不适用于破折号,但无法找到解决方案。

谢谢

import dash_html_components as html
import dash_core_components as dcc
import dash
import sqlite3
import plotly
import dash_table as dte
from dash.dependencies import Input, Output, State
import pandas as pd



app = dash.Dash()

app.scripts.config.serve_locally = True
app.config['suppress_callback_exceptions'] = True

app.layout = html.Div([

    html.H5("Upload Files"),
    dcc.Upload(
        id='upload-data',
        children=html.Div([
            'Drag and Drop or ',
            html.A('Select Files')
        ]),
        style={
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        multiple=False),
    html.Br(),
    html.Button(
        id='propagate-button',
        n_clicks=0,
        children='Propagate Table Data'
    ),


    html.Br(),
    html.H5("Filter Column"),
    dcc.Dropdown(id='dropdown_table_filterColumn',
        multi = False,
        placeholder='Filter Column'),


    html.Br(),
    html.H5("Updated Table"),
    html.Div(dte.DataTable(data=[{}], id='table'))


])



def parse_contents(contents, filename):

    try:
        if 'db' in filename:

            conn = sqlite3.connect(filename)
            df = pd.read_sql('SELECT Date, Triage FROM Database', con=conn)
            print(df)
    except Exception as e:
        print(e)
        return None

    return df



@app.callback(Output('table', 'data'),
              [Input('upload-data', 'contents'),
               Input('upload-data', 'filename')])
def update_output(contents, filename):
    if contents is not None:
        df = parse_contents(contents, filename)
        if df is not None:
            return df.to_dict('records')
        else:
            return [{}]
    else:
        return [{}]






app.css.append_css({
    "external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})

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

标签: pythonplotly-dash

解决方案


我个人喜欢为此使用类,但您可以使用字典或其他可变数据结构。

基本思想是在函数可以访问的范围内使用初始值初始化某种类型的可变数据结构。然后在应用程序生命周期的后期,我们可以改变数据。

class DbResult:
    def __init__(self, data=None):
        self.data = data

    def store(self, data):
        self.data = data


db_result = DbResult() 

>>> db_result.data
None

# db_result.data is None here because data wasn't passed to the constructor
# and we gave data an initial value of None

这允许我们db_result.store(data=df)在函数内部parse_contents调用。

设置好之后,我们可以在另一个函数中使用db_result.data.


推荐阅读