Hello please.

I would like to update the data for my gauge every time a user click on a 
button.

The data are simply variable from flask that I would like to use to draw 
the chart.

So far I know that I can use jinja2 to transfer them to my script but 
that's about it.

I don't know where to start please help.

My code is below :

app.py

from flask import Flask, request, render_template
from textblob import TextBlob
import requests, re
from bs4 import BeautifulSoup
from pprint import pprint


app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def rootpage():
    finalsub = None
    finalsent = None
    newsp = []
    if request.method == 'POST' and 'search-term' in request.form:
        SearchTerm = request.form.get('search-term')
        print(SearchTerm)
        a = Analysis(SearchTerm)
        a.run()
        print(a.term, 'Subjectivity: ', a.subjectivity, 'Sentiment: ', 
a.sentiment)
        finalsub = a.subjectivity
        finalsent = a.sentiment
        newsp = a.news
    return render_template("index.html", finalsub=finalsub, 
finalsent=finalsent, newsp=newsp)

class Analysis:
    def __init__(self, term):
        self.term = term
        self.subjectivity = 0
        self.sentiment = 0
        self.news = []
        self.url = 
'https://www.google.com/search?q={0}&source=lnms&tbm=nws'.format(self.term)

    def run(self):
            response = requests.get(self.url)
            # print(response.text)
            soup = BeautifulSoup(response.text, 'html.parser')
            mainDiv = soup.find("div", {"id": "main"})
            posts = [i for i in mainDiv.children][3:-2]

            for post in posts:
                reg = re.compile(r"^/url.*")
                cursor = post.findAll("a", {"href": reg})
                postData = {}
                postData["headline"] = cursor[0].find("div").get_text()
                postData["source"] = cursor[0].findAll("div")[1].get_text()
                postData["timeAgo"] = 
cursor[1].next_sibling.find("span").get_text()
                postData["description"] = 
cursor[1].next_sibling.find("span").parent.get_text().split("ยท ")[1]
                self.news.append(postData)
            pprint(self.news)
            for h in self.news:
                blob = TextBlob(h["headline"] + " " + h["description"])
                self.sentiment += blob.sentiment.polarity / len(self.news)
                self.subjectivity += blob.sentiment.subjectivity / 
len(self.news)

app.run()


index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sentiment Quick Check</title>
    <link rel="stylesheet" type="text/css" href="{{url_for('static', 
filename='style.css')}}">
    <link rel="stylesheet" 
href="https://unpkg.com/[email protected]/build/pure-min.css"; 
integrity="sha384-oAOxQR6DkCoMliIh8yFnu25d7Eq/PHS21PClpwjOTeU2jRSq11vu66rf90/cZr47"
 crossorigin="anonymous">
    <script type="text/javascript" 
src="https://www.gstatic.com/charts/loader.js";></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['gauge']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var finalsub = '{{finalsub}}'
        var finalsent = '{{finalsent}}'
        var data = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['Subjectivity', 80],
          ['Sentiment', 55],
        ]);

        var options = {
          width: 800, height: 240,
          redFrom: 180, redTo: 200,
          yellowFrom:150, yellowTo: 180,
          minorTicks: 10
        };

        var chart = new 
google.visualization.Gauge(document.getElementById('chart_div'));

        chart.draw(data, options);

        setInterval(function() {
          data.setValue(0, 1, 40 + Math.round(60 * Math.random()));
          chart.draw(data, options);
        }, 13000);
        setInterval(function() {
          data.setValue(1, 1, 40 + Math.round(60 * Math.random()));
          chart.draw(data, options);
        }, 5000);
        setInterval(function() {
          data.setValue(2, 1, 60 + Math.round(20 * Math.random()));
          chart.draw(data, options);
        }, 26000);
      }
    </script>
</head>
<body>
<h1>Google News Sentiment Analysis</h1>
<div class="posbox">
<form class="pure-form" method="POST" action="/">
    <input type="text" name="search-term" class="pure-input-2-3">
    <button class="button-secondary pure-button">Sentiment</button>
</form>
</div>
<br>
<div class="posbox2">
    <div class="childposbox1" id="chart_div" style="width: 400px; height: 
120px;"></div>
<br>
<div>
    {% if newsp %}
        <marquee behavior="scroll" direction="down">{{newsp}}</marquee>
    {% endif %}
</div>
</div>
</body>
</html>


The button in the form will be the one listening to the event.

Please help.

-- 
You received this message because you are subscribed to the Google Groups 
"Google Visualization API" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/google-visualization-api/3e80a3f8-b925-4523-9a27-a8279cd2e697%40googlegroups.com.

Reply via email to