Serving Banner Ads

Problem

You want to display banner ads by choosing images on the fly from a set of images.

Solution

Use a script that selects a random row from an image table and sends the image to the client.

Discussion

The display_image.pl script just shown assumes that the URL contains a parameter that names the image to be sent to the client. Another application might determine which image to display for itself. One popular image-related use for web programming is to serve banner advertisements for display in web pages. A simple way to do this is by means of a script that picks an image at random each time it is invoked. The following Python script, banner.py, shows how to do this, where the “ads” are the flag images in the image table:

#! /usr/bin/python # banner.py - serve randomly chosen banner ad from image table # (sends no response if no image can be found) import sys sys.path.insert (0, "/usr/local/apache/lib/python") import MySQLdb import Cookbook conn = Cookbook.connect ( ) try: query = "SELECT type, data FROM image ORDER BY RAND( ) LIMIT 1" cursor = conn.cursor ( ) cursor.execute (query) row = cursor.fetchone ( ) cursor.close ( ) if row is not None: (type, data) = row # Send image to client, preceded by Content-Type: and # Content-Length: headers. The Expires:, Cache-Control:, and # Pragma: headers help keep browsers from caching the image # and reusing it for sucessive requests for this script. print "Content-Type: %s" % type print "Content-Length: %s" % len (data) ...

Get MySQL Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.