I am experimenting with file_selector to upload a yaml file and want to make the uploaded content available to my main.py program and view the content on my webpage. Currently I defined a global variable that holds the read content like below:
from taipy.gui import Gui
import yaml
parsed_data = dict()
path = None
md = "<|{path}|file_selector|label=Upload file|on_action=load_yaml_file|extensions=.yaml|>"
def load_yaml_file(state):
global parsed_data
with open(state.path, 'r') as file:
yaml_data = file.read()
# Parse the YAML data into a dictionary
parsed_data = yaml.safe_load(yaml_data)
# other stuff
Gui(md).run()
What are other options instead of using a global variable?
You should use the state to display your variables.
Check out this section of the documentation to understand the state.
The state holds the value of all the variables used in the user interface for one specific connection.
from taipy.gui import Gui
import yaml
parsed_data = dict()
parsed_data_str = ""
path = None
md = """
<|{path}|file_selector|label=Upload file|on_action=load_yaml_file|extensions=.yaml|>
<|{parsed_data_str}|input|active=False|multiline|>
"""
def load_yaml_file(state):
with open(state.path, 'r') as file:
yaml_data = file.read()
# Parse the YAML data into a dictionary
state.parsed_data = yaml.safe_load(yaml_data)
state.parsed_data_str = yaml_data # you will see your yaml file as a string
# other stuff
Gui(md).run()
Now, you can retrieve state.parsed_data
with what you have put inside. The state is always a parameter of callbacks in Taipy.
I also tried to include the answer on the page.