Database Reference
In-Depth Information
my
$size
=
(
stat
(
$fh
))[
7
];
read
(
$fh
,
$data
,
$size
)
==
$size
or
error
(
"Failed to read entire file $image_path: $!"
);
$fh
->
close
();
}
$dbh
->
disconnect
();
# Send image to client, preceded by Content-Type: and Content-Length:
# headers.
print
header
(
-
type
=>
$type
,
-
Content_Length
=>
length
(
$data
));
print
$data
;
19.8. 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 shown in
Recipe 19.7
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
cookbook
conn
=
cookbook
.
connect
()
stmt
=
"SELECT type, data FROM image ORDER BY RAND() LIMIT 1"
cursor
=
conn
.
cursor
()
cursor
.
execute
(
stmt
)
row
=
cursor
.
fetchone
()
cursor
.
close
()