How to pause a graph in Plotly-Dash

I have a piechart that is polling data from an SQS queue on and an interval of 60 seconds. The piechart also deletes the message it just got to keep the queue clean and prevent duplicates. The SQS queue is being sent a new message every 40ish seconds, and the SQS queue is standard not FIFO. There is also a line graph that is displaying the sentiment of Twitter in real-time being updated on an interval of every second as well as a search bar that allows the user to search for a term (i.e. covid, biden, trump, etc.) and displays that term’s sentiment on the line graph. Every character a user enters updates the page since its querying the database. For example, if you type the term covid it search for "c" then "co" then "cov" and so on.

I am running into the problem that when a user does type in a term, the page refreshes on every character that is typed. This is fine for the line graph of live sentiment, but not for the piechart. When the page is refreshed, the piechart function is initiated and that means it polls the queue and deletes the message. So if somebody types a three-character term like "car" the piechart function will be activated three times and try and get/delete three messages. Since I have the ratio of a message being sent to the queue to the interval the piechart is refreshed set to 1:1, the piechart will have no messages to poll from.

Is there a way in dash-plotly to freeze a specific graph when a user is typing input into a search bar? Or, have a function not initiate when something is being typed in a search bar?

This is my code for the piechart and its update function:

def get_message():     sqs = boto3.client('sqs', aws_access_key_id=os.environ.get("accesskeyid"),                        aws_secret_access_key=os.environ.get("secretaccesskey"),                        region_name=os.environ.get("region"))      while True:         resp = sqs.receive_message(             QueueUrl=os.environ.get("queue_url"),             AttributeNames=['All'],             MaxNumberOfMessages=1         )          try:             data = []             messages = resp['Messages']             message = messages[0]             string_body_dictionary = message['Body']             body_dictionary = json.loads(string_body_dictionary)             string_message_dictionary = body_dictionary.get('Message')             sentiment_dictionary = json.loads(string_message_dictionary)             positive = sentiment_dictionary.get('Positive')             negative = sentiment_dictionary.get('Negative')             neutral = sentiment_dictionary.get('Neutral')             data.append(positive)             data.append(negative)             data.append(neutral)             entries = [                 {'Id': msg['MessageId'], 'ReceiptHandle': msg['ReceiptHandle']}                 for msg in resp['Messages']             ]              resp = sqs.delete_message_batch(                 QueueUrl=os.environ.get("queue_url"), Entries=entries             )              if len(resp['Successful']) != len(entries):                 raise RuntimeError(                     f"Failed to delete messages: entries={entries!r} resp={resp!r}"                 )             return data         except KeyError:             break   # @app.callback(Output('pie', 'figure'), #               [Input('pie-update', 'n_intervals')])  @app.callback(Output('pie', 'figure'),               [Input(component_id='sentiment_term', component_property='value')],               events=[Event('pie-update', 'interval')]) def update_pie(n):      try:          values = get_message()         labels = ['Positive', 'Negative', 'Mixed']          trace = go.Pie(labels=labels, values=values, title="Distribution of Twitter Sentiement",                        hoverinfo='label+percent', textinfo='value',                        textfont=dict(size=20, color=app_colors['text']),                        marker=dict(                            line=dict(color=app_colors['background'], width=2)))          return {'data': [trace], 'layout': go.Layout(title="Distribution of Twitter Sentiement",                                                      colorway=["#5E0DAC", '#FF4F00', '#375CB1', '#FF7400',                                                                '#FFF400',                                                                '#FF0056'],                                                      template='plotly_dark',                                                      paper_bgcolor='rgba(0, 0, 0, 0)',                                                      plot_bgcolor='rgba(0, 0, 0, 0)',                                                      margin={'b': 15},                                                      hovermode='x',                                                      autosize=True)}       except Exception as e:         with open('errors.txt', 'a') as f:             f.write(str(e))             f.write('\n') 
Asked on July 16, 2020 in Python.
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.