data_source_callbacks.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import base64
  2. import os
  3. from dash.dependencies import Input, Output, State, ALL
  4. from dash import html, callback_context
  5. from utils.file_utils import list_files_in_directory, save_file, delete_file, get_file_metadata
  6. from components.data_source import generate_data_source_table, DATA_SOURCE_DIR
  7. def register_data_source_callbacks(app):
  8. @app.callback(
  9. Output('data-source-upload-status', 'children'),
  10. [
  11. Input('upload-data', 'contents'),
  12. Input({'type': 'delete-data-source-button', 'index': ALL}, 'n_clicks')
  13. ],
  14. [
  15. State('upload-data', 'filename'),
  16. State('upload-data', 'last_modified'),
  17. State({'type': 'delete-data-source-button', 'index': ALL}, 'id')
  18. ]
  19. )
  20. def manage_data_source_files(contents, filenames, last_modified, delete_ids):
  21. ctx = callback_context
  22. if not ctx.triggered:
  23. return html.Div()
  24. triggered_id = ctx.triggered[0]['prop_id'].split('.')[0]
  25. if 'upload-data' in triggered_id and contents:
  26. for content, filename in zip(contents, filenames):
  27. data = content.split(",")[1]
  28. save_file(DATA_SOURCE_DIR, filename, base64.b64decode(data))
  29. files = list_files_in_directory(DATA_SOURCE_DIR)
  30. return generate_data_source_table(files)
  31. elif 'delete-data-source-button' in triggered_id:
  32. for item in delete_ids:
  33. if item['id'] == triggered_id:
  34. file_path = os.path.join(DATA_SOURCE_DIR, item['index'])
  35. delete_file(file_path)
  36. files = list_files_in_directory(DATA_SOURCE_DIR)
  37. return generate_data_source_table(files)
  38. return html.Div()