Da sh Обратный вызов внутри функций - PullRequest
0 голосов
/ 11 февраля 2020

Как вы можете видеть ниже, у меня есть приложение Da sh, которое генерирует маршруты по функциям, однако мои обратные вызовы для выполнения табличных вычислений не работают как expectet.

Я пытался разрешить обратный вызов этого приложения раньше и после обратных вызовов, которые обновляют таблицы, однако это не работает также.

Как причина, по которой эти обратные вызовы перестают работать, также есть в любом случае, чтобы сделать эту работу снова?

У меня есть функция диспетчера, что параметры запроса, также у меня есть функция, которая создает приложение, и функции, которые генерируют маршруты (страницы) в моем приложении.

import sys
from random import randint
import base64
import io

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
from os import listdir
from dash.dependencies import Input, Output, State

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("Dashboard", className="ml-2", href="/dash-fig1")),
                        ],
                        align="center",
                        no_gutters=True,
                    ),
                    href="https://plot.ly",
                ),

                 dhc.A(
                    dbc.Row([
                     dbc.Col(dcc.Link("Home", 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=False),
        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'

    return app

    @app.callback(Output('output-data-upload', 'children'),
            [Input('upload-data', 'contents')],
            [State('upload-data', 'filename'),
            State('upload-data', 'last_modified')])
    def update_output(list_of_contents, list_of_names, list_of_dates):
        if list_of_contents is not None:
            children = [
                parse_contents(c, n, d) for c, n, d in
                zip(list_of_contents, list_of_names, list_of_dates)]
            return children
        else:
            PreventUpdate



    @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'] = 'NA'

        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



def dash_index():
    ''' '''
    return 'Welcome to index page'


def dash_fig1():

    return  dhc.Div([
            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},


                ),

                    ],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},


                ),

                    ],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},


                ),

                    ],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},


                ),

                    ],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/>

            #Tabela UPPH<

            dhc.Div([
            dhc.Div([ 
                dhc.H2(children = "UPH por Pessoa / Hora (Canal)",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),


                dash_table.DataTable(
                            id='tableUPPH',
                            columns=[{"name": i, "id": i} for i in tabelaupph2.columns],
                            data=tabelaupph2.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},


                ),

                    ],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 UPPH/>




            #Mos Prod hora estacao & prod hora operador<


            dhc.Div([
                    dhc.Div([
                        dhc.H3('Produção Por Estação / Hora'),
                        dcc.Graph(id='chart1', figure= figure3)
                    ], className="six columns", style= {'width': '100%','textAlign' : 'center', 
                                                        'marginBottom': 50, 'marginTop': 25, 
                                                        'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)', 
                                                        'padding': '30px 20px', 'display': 'flex',
                                                    'display': 'inline-block',
                                                    'flexDirection': 'row'}),

                    dhc.Div([
                        dhc.H3('Produção Por Pessoa / Hora'),
                        dcc.Graph(id='chart2', figure=figure4)
                    ], className="six columns", style= {'width': '100%', 'textAlign' : 'center',
                                                        'marginBottom': 50, 'marginTop': 25,
                                                        'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                                        'padding': '30px 20px', 'display': 'flex', 
                                                        'display': 'inline-block',
                                                    'flexDirection': 'row'}),

                ], className="row", style={'display': 'flex', 'flexWrap': 'nowrap', 'flexDirection': 'row'}),



            #Mos Prod hora estacao & prod hora operador/>


            #Tabela tipo produto por cut off<

            dhc.Div([
            dhc.Div([ 
                dhc.H2(children = "Visão Geral - Tipo de Produto Por Cut Off",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),


                dash_table.DataTable(
                    id='table-prod',
                    columns=[{"name": i, "id": i} for i in dfprod.columns ],
                    data=dfprod.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},


                ),

                    ],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 tipo de produto por cur off/>       




            #Prod Hora Canal<

            dhc.Div([ 


            dhc.Div([
            dhc.Div([ 

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

                dhc.Br(""),

                    dcc.Graph( id = 'GrapGo', figure = figure2),
                    ],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 Canal/> 






            #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'}),

    @app.callback(Output('output-data-upload', 'children'),
        [Input('upload-data', 'contents')],
        [State('upload-data', 'filename'),
        State('upload-data', 'last_modified')])
    def update_output(list_of_contents, list_of_names, list_of_dates):
        if list_of_contents is not None:
            children = [
                parse_contents(c, n, d) for c, n, d in
                zip(list_of_contents, list_of_names, list_of_dates)]
            return children
        else:
            PreventUpdate



    @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'] = 'NA'

        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


def dash_fig2():
    ''' '''
    return '2'


def dash_fig3():

    return "3"

if __name__ == '__main__':
    app = _create_app()
    app.run_server()

...