【问题标题】:Function Callbacks Not Working on Multipage Dash/Django Application函数回调不适用于多页 Dash/Django 应用程序
【发布时间】:2020-06-01 18:47:52
【问题描述】:

我有下面使用破折号情节的应用程序。

如果我在单个文件/页面应用程序中执行此应用程序,所有回调都会正常工作。

但在这种情况下,我将 dash 多页应用程序与 Django 一起使用。

我的回调停止工作,computed-tabletable-backlog

我不确定为什么这些回调不起作用,因为运行时或代码中也没有错误。

回调的目的是在用户更改值后在dash table中执行计算。

完整项目:https://github.com/CaioEuzebio/DjangoDashboard/blob/master/app/as_dash.py

应用:

import sys
from random import randint
import base64
import io
import datetime

from dash.dependencies import Input, Output, State

import dash

import dash_core_components as dcc
import dash_html_components as dhc

import pandas as pd
import random
import plotly.graph_objects as go
import dash_table
import dash_table_experiments
import dash_table
import dash_bootstrap_components as dbc
import os, time
from os import listdir
import os.path, time
import datetime
import subprocess




from website.views import *





PLOTLY_LOGO = "https://p7.hiclipart.com/preview/243/790/417/doing-business-as-company-logo-name-creative-company-logo.jpg"


def dispatcher(request):
    '''
    Main function
    @param request: Request object
    '''

    app = _create_app()
    params = {
        'data': request.body,
        'method': request.method,
        'content_type': request.content_type
    }
    with app.server.test_request_context(request.path, **params):
        app.server.preprocess_request()
        try:
            response = app.server.full_dispatch_request()
        except Exception as e:
            response = app.server.make_response(app.server.handle_exception(e))
        return response.get_data()
    
    


def _create_app():

    ''' Creates dash application '''

    app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
    app.config['suppress_callback_exceptions']=True
    app.layout = dhc.Div(children=[

                dbc.Navbar(
            [
                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [
                            dbc.Col(dhc.Img(src=PLOTLY_LOGO, height="30px")),
                            dbc.Col(dcc.Link("Home", className="ml-2", href="/home", refresh=True)),
                        ],
                        align="center",
                        no_gutters=True,
                    
                    ),href="/home"
                ),
                
                
                
                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [
                            
                            dbc.Col(dcc.Link("Dashboard", className="ml-2", href="/dash-fig1")),
                        ],
                        align="center",
                        no_gutters=True,
                    ),
                    href="/home",
                ),
                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [
                            
                            dbc.Col(dcc.Link("Dashboard S.", className="ml-2", href="/dash-fig2")),
                        ],
                        align="center",
                        no_gutters=True,
                    ),
                   
                ),

                 dhc.A(
                    dbc.Row([
                     dbc.Col(dcc.Link("Load New File", className="ml-2", href="/loadfile", refresh=True)), 
                     ],
                        align="center",
                        no_gutters=True,
                    ), href="/loadfile"
                 ),
                 
                  
                
                
                dbc.NavbarToggler(id="navbar-toggler"),
              
            ],
            color="dark",
            dark=True,
        ),

        dcc.Location(id='url', refresh=True),
    
        dhc.Br(),
        dhc.Br(),
        dhc.Div(id='content'),
    ])


    

    @app.callback(dash.dependencies.Output('content', 'children'),
                [dash.dependencies.Input('url', 'pathname')],               
    )
    
    def display_page(pathname):

        
        ''' '''
        if not pathname:
            return ''
        if pathname == '/':
            return dash_index()
        method = pathname[1:].replace('-', '_')
        func = getattr(sys.modules[__name__], method, None)
        if func:
            return func()
        return 'Unknown link'
    
    @app.callback(
        Output('computed-table', 'data'),
        [Input('computed-table', 'data_timestamp')],
        [State('computed-table', 'data')])
    def update_columns(timestamp, rows):
        for row in rows:
            try:
                if row['Unidades Pendentes'] != 0:
                    row['UPH_BPI_vs_Head'] = float(row['UPH_BPI_vs_Perfil']) * float(row['Head_Disponível'])
                    row['ETA_Geral'] = float(row['Unidades Pendentes']) / float(row['UPH_BPI_vs_Head'])
                    row['Delta_Hora'] = float(row['Horas_Disp']) - float(row['ETA_Geral'])
                    row['Risco_Aging'] = float(row['Delta_Hora']) * float(row['UPH_BPI_vs_Head'])
                else:
                    row['UPH_BPI_vs_Head'] = "Completed"
                    row['ETA_Geral'] = "Completed"
                    row['Delta_Hora'] = "Completed"
                    row['Risco_Aging'] = "Completed"
                    row['UPH_BPI_vs_Perfil'] = "Completed" 
                    row['Head_Disponível'] = "Completed"
                    row['Horas_Disp'] = "Completed" 
            except:
                row['ETA_Geral'] = 'N/A'
                
        return rows


    



    @app.callback(
        Output('table-backlog', 'data'),
        [Input('table-backlog', 'data_timestamp')],
        [State('table-backlog', 'data')])
    def update_columns(timestamp, rows):
        for row in rows:
            try:
                if row['Unidades Pendentes'] != 0:
                    row['Delta Hora'] = float(row['Horas Disp']) - float(row['ETA'])
                    row['Risco Aging'] = float(row['Delta Hora']) * float(row['UPH'])
                else:
                    row['ETA'] = "Completed"
                    
            except:
            
                row['ETA'] = row['ETA']
        return rows

    return app


    
    
    

  
    



def dash_fig1():

    #pandas code
   
    return  dhc.Div([
            dhc.Div([ dhc.H2(children= 'Nome Do Aqrquivo: ' + filename ),
            dhc.H2(children= "Date created: " + dataa),
            
            ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px',
                            'marginBottom': 50} ),
            dhc.Div([
            dhc.Div([ 

                dhc.H2(children = "Perfil Por Canal",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),
            
                    
            dash_table.DataTable(
                    id='table1',
                    columns=[{"name": i, "id": i} for i in dforderbypn.columns],
                    data=dforderbypn.to_dict('records'),
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True


                ),

            ]

                    ,style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),
                
                    ],style={'textAlign': 'center' }),      
                        
            #Tabela De Perfil Por Canal/>        

                    
                    


            #Tabela De Desempenho Por Canal<

            dhc.Div([
            dhc.Div([ 

                dhc.H2(children = "UPH / ETA  Médio Por Canal",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),
            
                    
            dash_table.DataTable(
                    id='table1',
                    columns=[{"name": i, "id": i} for i in dfordertype.columns],
                    data=dfordertype.to_dict('records'),
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True


                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),
                
                    ],style={'textAlign': 'center', 'marginTop': '15px'}),      
                    

                    
            #Tabela De Desempenho Por Canal/>

                
                    
                    
            #Planejamento Estilizado<        
            dhc.Div([
            dhc.Div([ 

                    dhc.H2(children = "Planner - Suporte",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),
            
                    
                dash_table.DataTable(
                    id='computed-table',
                    columns=[{"name": i, "id": i} for i in dfplano.columns ],
                    data=dfordertype.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True


                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),
                
                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),
            #Planejamento Estilizado/>


                    
                    
            # Tabela Gerenciamento de Backlog<      
                    
            dhc.Div([
            dhc.Div([ 
                dhc.H2(children = "Status Por Cut Off",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),
            
                    
                dash_table.DataTable(
                    id='table-backlog',
                    columns=[{"name": i, "id": i} for i in tabelaback.columns ],
                    data=tabelaback.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True


                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),
                
                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),
                    
                    
                    
            # Tabela Gerenciamento de Backlog/>

            
                

                
            #Prod Hora Estaao<

                
            dhc.Div([
                dhc.Div([ 

                        dhc.H3(children = "Produção Por Hora (Estação)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo2', figure = figure3),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),    
                
            #Prod Hora Estacao/> 
                    
            

                
            #Prod Hora Operador<

                
            dhc.Div([
                dhc.Div([ 

                        dhc.H3(children = "Produção Por Hora (Pessoa)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph( id = 'GrapGo3', figure = figure4),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),    
                
            #Prod Hora Operador/>     
                

            
                
            #Medias moveis<
            dhc.Div([
                dhc.Div([ 

                        dhc.H3(children = "Médias Mveis (10, 20 e 30 periodos)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figuremm),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}), 

            #Medias moveis/>



            #Media 10 intervalos<
            dhc.Div([
                dhc.Div([ 

                        dhc.H3(children = "Médias Móveis - 10 Intervalos por canal",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figure7),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}), 

            #Media 10 intervalos/>




            #Unidades Recebidas Vs Processadas/hora<
            dhc.Div([
                dhc.Div([ 

                        dhc.H3(children = "Unidades Recebidas Vs Processadas por Hora (Drop)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figurefd),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}), 
            #Unidades Recebidas Vs Processadas/hora/>


            


            #UPPH Chart<
            dhc.Div([
                dhc.Div([ 

                        dhc.H3(children = "Unidade Produzidas Por Pessoa (Hora)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figure52)
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}), 
            #UPPH chrta/>







            ], style={'marginBottom': 50, 
                        'marginTop': 50, 
                        'textAlign': 'center', 
                        'padding': '30px 20px', 
                        'align-items': 'center' }),



            ], style={'marginLeft': 50, 
                        'marginRight': 50, 
                        'display':'block', 
                        'textAlign': 'center', 
                        'align-items': 'center',
                        'padding': '30px 20px'})

        



    


def dash_fig2():
    


    return dhc.Div([
            dhc.Div([
                dhc.Div(children=[dhc.H1('Dash 2')
                                
                                
                                
                                
                                ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),
            
            dhc.Div([
            dhc.Div([ 

                    dhc.H2(children = "Planner - Suporte",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),
            
                    
                dash_table.DataTable(
                    id='computed-table',
                    columns=[{"name": i, "id": i} for i in dfplano.columns ],
                    data=dfordertype.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True


                )

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),
                
                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),



            ], style={'marginBottom': 50, 
            'marginTop': 50, 
            'textAlign': 'center', 
            'padding': '30px 20px', 
            'align-items': 'center' }),



            ], style={'marginLeft': 50, 
                        'marginRight': 50, 
                        'display':'block', 
                        'textAlign': 'center', 
                        'align-items': 'center',
                        'padding': '30px 20px'})








def dash_fig3():

    return 'a'


if __name__ == '__main__':
    app = _create_app()
    app.run_server(threaded=True, dev_tools_hot_reload=False)

【问题讨论】:

    标签: python django pandas plotly-dash


    【解决方案1】:

    在多页应用程序中,您可以将所有回调放在一个 py 文件中,例如 callbacks.py。如果您按照 dash 文档中的建议拆分了多页应用程序,并且有一个 app.py、index.py,那么您需要在 callback.py 中拥有

    from app import app 
    

    那么在index.py中你需要有

    import callback
    

    尝试以这种方式分离代码并确保在 index.py 中有导入回调,它应该可以工作。

    【讨论】:

    • 感谢您的建议。我会尝试这种模式并返回我的结果。
    • 我试过了,我没有得到结果,我瘦是因为我也使用了 django。
    • 您能否发布关于您如何为应用程序分成多个文件的 sn-ps?也尝试打印你从回调中的点击中获得的内容,这将有助于调试
    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2022-07-01
    • 2021-07-14
    • 1970-01-01
    • 2020-12-09
    • 2021-02-14
    相关资源
    最近更新 更多