This script is intended to be run as a CGI in a web server.
[CGI Version] pythondemo_cgi\simplebar.py
#!/usr/bin/python from pychartdir import * # The data for the bar chart data = [85, 156, 179.5, 211, 123] # The labels for the bar chart labels = ["Mon", "Tue", "Wed", "Thu", "Fri"] # Create a XYChart object of size 250 x 250 pixels c = XYChart(250, 250) # Set the plotarea at (30, 20) and of size 200 x 200 pixels c.setPlotArea(30, 20, 200, 200) # Add a bar chart layer using the given data c.addBarLayer(data) # Set the labels on the x axis. c.xAxis().setLabels(labels) # output the chart print "Content-type: image/png\n" binaryPrint(c.makeChart2(PNG)) |
The code is almost identical to the code in The First Project, so the details will not be further explained. The major difference is that instead of using BaseChart.makeChart to output the chart as a PNG file, it outputs the chart as a binary string using BaseChart.makeChart2 and streams the data directly to the browser.
The chart image is streamed to the browser using the following code:
print "Content-type: image/png\n" binaryPrint(c.makeChart2(PNG))
The above code first prints the MIME Content-type header, and then use pychartdir.binaryPrint to print out the binary image for delivery to the browser.
pychartdir.binaryPrint is a ChartDirector utility for binary printing, which solves two problems with the Python "print" statement when printing binary images:
- On Windows, by default, the "print" statement will print in text mode. It will replace [LF] with [CR][LF], and will corrupt a binary image. The "binaryPrint" statement always print in binary mode.
- The "print" statement will automatically append a new line character at the end of the output, which is incorrect for a binary image. The "binaryPrint" statement will not append any character at the end.