Quantcast
submit to reddit       
       

Using Google charts in Python CGI scripts

A common use of the Raspberry Pi is data logging. People use them to monitor temperatures, voltages, weather conditions, and all sorts of other things. Once you've collected data, you need some way to display it. Google provide Javascript code to embed charts in your site.

In this eaxmple I'm going to use a Python script to read data from a file and display a page with a Javascript chart in it. The chart will have dates along the x-axis and a count along the y-axis. The count could be the number of hits to a web site, the number of times a button has been pressed, or anything you want. The data used in this example is stored in a text file in /var/www/data.txt. It's format is as follows:

yyyy.mm.dd;value

The complete data set for this example looks like this:

2013.07.01;23
2013.07.02;67
2013.07.03;45
2013.07.04;17
2013.07.05;56

The date will be used to label each column, and the height of each column is determined by the value. You don't have to use the date - any string will do. You could use names if you wanted. When I created data.txt, I changed its owner so that Apache can access it:

$ sudo chown www-data:www-data /var/www/data.txt

I wrote a script called chart.py and stored it in /usr/lib/cgi-bin.

#!/usr/bin/env python import cgi import cgitb # enable tracebacks of exceptions cgitb.enable() # print data from a file formatted as a javascript array # return a string containing the table #  def print_table(filename,delimiter):     data_lines=[]     result=""     with open(filename) as data_file:         data_lines=data_file.readlines()         for line in data_lines[:-1]:             x, y=line.strip('\n').split(delimiter)             result += "['"+x+"', "+y+"],\n"         else:             x, y=data_lines[-1].strip('\n').split(delimiter)             result += "['"+x+"', "+y+"]"     return result # print an HTTP header # def printHTTPheader():     print "Content-type: text/html"     print ""     print "" def main():     printHTTPheader()     # this string contains the web page that will be served     page_str="""     <h1>Charts with Python and Javascript</h1>     <script type="text/javascript" src="https://www.google.com/jsapi"> </script>     <script type="text/javascript">       google.load("visualization", "1", {packages:["corechart"]});       google.setOnLoadCallback(drawChart);       function drawChart() {         var data = google.visualization.arrayToDataTable([     ['Date', 'Count'],     %s          ]);         var options = {           title: 'Google column chart',           hAxis: {title: 'Date', titleTextStyle: {color: 'blue'}},           vAxis: {title: 'Count', titleTextStyle: {color: 'blue'}}         };         var chart = new google.visualization.ColumnChart                 (document.getElementById('chart_div'));         chart.draw(data, options);       }     </script>     <div id="chart_div"></div>     </body>     """ % print_table('/var/www/data.txt', ';')     # serve the page with the data table embedded in it     print page_str if __name__=="__main__":     main()

I made the file executable with this command:

$ sudo chmod +x /usr/lib/cgi-bin/chart.py

The Python script generates the pagesent by the server, and the Javascript code is executed in the browser.

Chart.py starts in main() by printing an HTTP header so that the browser knows that the folloing text is HTML. The variable page_str is a string that contains all the HTML and Javascript for the page. The array that stores the data for the chart is inserted at the position marked by %s in page_str. The text substituted here is the table returned by a call to print_table().

This function opens data.txt and reads the data contained in it. A 'for' loop is used to read the file line by line. The strip and split methods are used to remove the trailing newline and break the string into tuples. The tuples are then formatted like this:

['x', y],

Each of these newly formed strings is appended to a larger string that contains the whole table. Note that the last line doesn't need to have a comma at the end of it, so it needs to be handled differently than the other lines. The for loop executes for all but the last line. The 'else' statement after the loop handles the last line, and formats it without a comma at the end.

Once the table has been inserted into the string and the string has been received by a browser, the Javascript code will execute and display the graph. I pointed my browser to http://192.168.0.4/cgi-bin/chart.py.

Charts with Python and Javascript

Each chart has options that can be used to customize the way data is displayed. For different types of chart you may need to to modify the format of the table generated by the script. You can find more at Google Charts.

The Javascript code for the column chart is from this page.


Comments

Comments

comments powered by Disqus



Follow me