как выполнить обратный звонок для Upload Control в Da sh -Plotly, чтобы обновить базу данных или создать таблицу в базе данных - PullRequest
2 голосов
/ 13 января 2020

У меня есть простой код, который имеет управляющую кнопку Загрузить, используя Dash-Plotly Frameworkout в качестве кода ниже

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

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Upload(
        id='upload-xlsx-file',
        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'
        },
        # Allow multiple files to be uploaded
        multiple=True
    ),

])

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

Так как выполнить @app.Callback для функции кода ниже

# reading and insert one file at a time
for file in os.listdir('.'):
    # only process excels files
    file_basename, extension = file.split('.')
    if extension == 'xlsx':
        lte_details.to_sql(file_basename.lower(), con=engine.connect(), if_exists='replace')

как я пытался сделать что-то подобное, но результата нет, пожалуйста, проверьте приведенный ниже полный код

import datetime
import pyodbc
import pandas as pd
import os
from sqlalchemy import create_engine
import datetime as dt
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# connect db
engine = create_engine('mssql+pyodbc://.........../myDB?driver=SQL+Server+Native+Client+11.0')
cursor = engine.raw_connection().cursor()


mydir = (os.getcwd()).replace('\\', '/') + '/'

lte_details = pd.read_excel(r'' + mydir + 'input.xlsx', sheet_name='LTE Details')

lte_details['Date'] = pd.to_datetime(lte_details['Date'], errors='coerce')

lte_details.columns = [''.join(e for e in x if e.isalnum()) for x in lte_details.columns]

app.layout = html.Div([
    dcc.Upload(
        id='upload-xlsx-file',
        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'
        },
        # Allow multiple files to be uploaded
        multiple=True
    ),

    html.Div(id='output-data-upload'),

])




@app.callback(Output('output-data-upload', 'children'))
def update_db():
    # reading and insert one file at a time
    for file in os.listdir('.'):
        # only process excels files
        file_basename, extension = file.split('.')
        if extension == 'xlsx':
            lte_details.to_sql(file_basename.lower(), con=engine.connect(), if_exists='replace')
        return update_db

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

Я не знаю, как это сделать ...

Я благодарен за то, что кто-то поддерживает меня ...

Надеюсь, это будет достаточно ясно.

...