putting Image from database in cgi app
Fredrik Lundh
fredrik at pythonware.com
Wed May 21 08:37:10 EDT 2003
"vivek kumar" wrote:
> >vivek kumar wrote:
> >> I was wondering if there is any way to show the file read from database
> >>in the cgi app..
> ...
> >>like: cur.execute("select pic from pictest where id=1")
> >> rst=cur.fetchone()
> >> s=open("temp.jpg","wb")
> >> s.write(rst[0])
> >> s.close
> >> print '<img src="temp.jpg">'
> >>
> >>So, I was wondering if there is any way in which I can show the file
> >>directly without creating an intermediate file???
>
> >Sure, but one HTTP request can only deliver one resource to the client, be
> >it a HTML document or a JPEG image.
> >
> >A CGI script that would deliver a JPEG image to the client could look like
> >this:
> >
> >#v+
> >...
> >cu = cx.cursor()
> >cu.execute("SELECT PIC FROM PICTEST WHERE ID=1")
> >img = cu.fetchone()[0]
> >
> >print "Content-type: image/jpeg\n"
> >print img
> >
> >cx.close()
> >#v+
> >
> >-- Gerhard
>
> THX a lot for that. But what I want to do is to show the image with some
> related data. I am working on a shopping cart typo thing (Book Store) and I
> want to show the image with various details like book name,author etc with
> the Image (like an IMG tag in a HTML document). Is it possible to do it
> without creating a temporary file??
you need two different CGI's (or two different code paths in the
same CGI).
the main CGI generates the HTML page, with all the information you
need, and a reference to the image. the user's browser will render
the HTML, and issue a request for the image (unless the user has
switched off image loading, or uses a text-only browser, etc).
the other CGI returns the image, if and when the browser asks for it.
example:
first cgi:
cur.execute("select info from infotest where id=%s", identity)
print "<h3>Description</h3>"
print cgi.escape(cur.fetchone()[0])
print "<h3>Image</h3>"
print "<img src='/somecleverpath/myother.cgi/image/%s' />" % identity)
second cgi:
identity = extract_identity_from_url()
cur.execute("select pic from pictest where id=%s", identity)
... insert gerhard's code here ...
</F>
More information about the Python-list
mailing list