[Tutor] getting an image out of a postgre database

Mike Hansen mhansen at cso.atmel.com
Thu Jun 23 16:20:56 CEST 2005

Well, I've managed to get an image into a postgre database, but now I'm having 
trouble getting it out.

#! /usr/bin/env python

from pyPgSQL import PgSQL

def main():
     connectdb = PgSQL.connect('server:port:database:username:password')
     cur = connectdb.cursor()
     sqlStatement = """SELECT image from images where image_id = 1"""
     rec = cur.fetchone()
     # TODO make temp file name include image_id.
     # TODO use tempfile module
     # TODO clean up old temp files
     tempFileName = "1.jpg"
     tempFile = open(tempFileName, "w")

     print "Content-type: text/html\n\n"
     print """"<?xml version="1.0" encoding="windows-1250"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="http://www.w3.org/1999/xhtml">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1250" />

<img src="1.jpg">

if __name__ == '__main__':

Traceback (most recent call last):
   File "./dispimage.py", line 39, in ?
   File "./dispimage.py", line 16, in main
TypeError: argument 1 must be string or read-only character buffer, not instance

So, rec[0] is an instance, but an instance of what? Since I needed to use the 
PgSQL.PgBytea method on the image before inserting it into the database, do I 
need to use a similar method to undo what PgBytea did to it, or am I incorrectly 
writing this binary data? I tried PgSQL.PgUnQuoteBytea(rec[0]), but that didn't 

If this is more appropriate for another mail list, let me know.


More information about the Tutor mailing list