Pages

Monday, March 29, 2010

Interactive Chart from Google Apps Engine datastore

Create a simple python file chart.py which should have been already mapped to a particular URL pattern in app.yamx

- url: /chart/.*
  script: chart.py

   1: import cgi



   2:  



   3: from google.appengine.ext import db



   4: import hist



   5:  



   6: import os



   7: from google.appengine.ext.webapp import template



   8:  



   9: quotes = db.GqlQuery("SELECT * FROM HistoricalPrices")



  10:  



  11: template_values = {'quotes': quotes,}



  12:  



  13: path = os.path.join(os.path.dirname(__file__), 'index.html')



  14: print template.render(path, template_values)




index.html should look like following





   1: <html>



   2:   <head>



   3:     <script type="text/javascript" src="http://www.google.com/jsapi"></script>
   1:  
   2:     <script type="text/javascript">
   3:       google.load("visualization", "1", {packages:["linechart"]});
   4:       google.setOnLoadCallback(drawChart);
   5:       function drawChart() {
   6:         var data = new google.visualization.DataTable();
   7:         data.addColumn('string', 'Year');
   8:         data.addColumn('number', 'Sales');
   9:         {% for quote in quotes %}        
  10:         data.addRows(1);
  11:         data.setValue({{ forloop.counter0  }}, 0, '{{ quote.TIMESTAMP }}');
  12:         data.setValue({{ forloop.counter0  }}, 1, {{ quote.OPEN }});
  13:         {% endfor %}
  14:         var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  15:         chart.draw(data, {width: 400, height: 240, legend: 'bottom', title: 'Company Performance'});
  16:       }
  17:     
</script>



   4:   </head>



   5:   <body>



   6:     <div id="chart_div"></div>      



   7:         <b></b>



   8:   </body>



   9: </html>




Here Django's templating engine is used. For the charting component Google Visualization API is used.



Following command can be used for single command update



D:\Python\python.exe "D:\\Program Files\\Google\\google_appengine\\appcfg.py" --passin --email=<username>@gmail.com update "D:\\dev\\appsengine\\proxy"  < gpass



Here gpass is a text file containing the password.