ChartDirector Ver 5.0 (Python Edition)

Direct Database Access




In this example, we will demonstrate how to create a web page to show the monthly revenue for a given year. The user will select a year from a HTML form and press OK. The web server will query a database to obtain the necessary data, and return a web page containing the bar chart for the selected year.

The code for producing the HTML form is listed below. It outputs a drop down select list to allow the user to select a year. Based on the selected year, it uses an <IMG> tag with a ChartDirector script as the URL and the selected year as query parameter. The ChartDirector script will generate the chart image based on the selected year and deliver it to the browser.

[CGI Version] pythondemo_cgi\dbdemo1.py
#!/usr/bin/python
from pychartdir import *
import cgi

# Get HTTP query parameters
query = cgi.FieldStorage()

# The currently selected year
try :
    selectedYear = int(query["year"].value)
except :
    selectedYear = 2005

#
# The following code generates the <option> tags for the HTML select box, with the
# <option> tag representing the currently selected year marked as selected.
#

optionTags = [None] * (2005 - 1994 + 1)
for i in range(1994, 2005 + 1) :
    if i == selectedYear :
        optionTags[i - 1994] = "<option value='%s' selected>%s</option>" % (i, i)
    else :
        optionTags[i - 1994] = "<option value='%s'>%s</option>" % (i, i)
selectYearOptions = string.join(optionTags, "")

print("Content-type: text/html\n")
print("""
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Database Integration Demo (1)
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20px">
• <a href="viewsource.py?file=%(SCRIPT_NAME)s">
    View containing HTML page source code
</a>
<br />
• <a href="viewsource.py?file=dbdemo1a.py">
    View chart generation page source code
</a>
<br />
<br />
<form>
    I want to obtain the revenue data for the year
    <select name="year">
        %(selectYearOptions)s
    </select>
    <input type="submit" value="OK">
</form>
</div>

<img src="dbdemo1a.py?year=%(selectedYear)s">

</body>
</html>
""" % {
    "SCRIPT_NAME" : os.environ["SCRIPT_NAME"],
    "selectYearOptions" : selectYearOptions,
    "selectedYear" : selectedYear
    })

As seen from the code above, the chart is created by the URL in the <IMG> tag, which is "dbdemo1a.py". The source code of "dbdemo1a.py" is as follows.

[CGI Version] pythondemo_cgi\dbdemo1a.py
#!/usr/bin/python
from pychartdir import *
import cgi

# Get HTTP query parameters
query = cgi.FieldStorage()

#
# Displays the monthly revenue for the selected year. The selected year should be
# passed in as a query parameter called "year"
#
try :
    selectedYear = int(query["year"].value)
except :
    selectedYear = 2005

#
# Query the database to get monthly reveunes for software, hardware and services for
# the year. In this demo, we will use random numbers instead of a real database.
#
rantable = RanTable(selectedYear, 3, 12)
rantable.setCol(0, 30 * (selectedYear - 1990),  80 * (selectedYear - 1990))
rantable.setCol(1, 30 * (selectedYear - 1990),  80 * (selectedYear - 1990))
rantable.setCol(2, 30 * (selectedYear - 1990),  80 * (selectedYear - 1990))

software = rantable.getCol(0)
hardware = rantable.getCol(1)
services = rantable.getCol(2)

#
# Now we have read data into arrays, we can draw the chart using ChartDirector
#

# Create a XYChart object of size 600 x 300 pixels, with a light grey (eeeeee)
# background, black border, 1 pixel 3D border effect and rounded corners.
c = XYChart(600, 300, '0xeeeeee', '0x000000', 1)
c.setRoundedFrame()

# Set the plotarea at (60, 60) and of size 520 x 200 pixels. Set background color to
# white (ffffff) and border and grid colors to grey (cccccc)
c.setPlotArea(60, 60, 520, 200, '0xffffff', -1, '0xcccccc', '0xccccccc')

# Add a title to the chart using 15pts Times Bold Italic font, with a light blue
# (ccccff) background and with glass lighting effects.
c.addTitle("Global Revenue for Year %s" % (selectedYear), "timesbi.ttf", 15
    ).setBackground('0xccccff', '0x000000', glassEffect())

# Add a legend box at (70, 32) (top of the plotarea) with 9pts Arial Bold font
c.addLegend(70, 32, 0, "arialbd.ttf", 9).setBackground(Transparent)

# Add a stacked bar chart layer using the supplied data
layer = c.addBarLayer2(Stack)
layer.addDataSet(software, '0xff0000', "Software")
layer.addDataSet(hardware, '0x00ff00', "Hardware")
layer.addDataSet(services, '0xffaa00', "Services")

# Use soft lighting effect with light direction from the left
layer.setBorderColor(Transparent, softLighting(Left))

# Set the x axis labels. In this example, the labels must be Jan - Dec.
labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
    "Nov", "Dec"]
c.xAxis().setLabels(labels)

# Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5)

# Set the y axis title
c.yAxis().setTitle("USD (Millions)")

# Set axes width to 2 pixels
c.xAxis().setWidth(2)
c.yAxis().setWidth(2)

# Output the chart in PNG format
print("Content-type: image/png\n")
binaryPrint(c.makeChart2(PNG))

The first part of the above code simulates a database query by using random numbers. The second part of the code is to create a stacked bar chart using the data. This is very similar to the examples in other parts of this documentation, so it will not be explained further.