If you need to convert a TEXT column to a BYTEA column, you can use a cast expression to do the work:
ALTER TABLE mytable ALTER COLUMN col TYPE bytea USING decode(replace(col, '\\', '\\\\'), 'escape');
Note that altering the column type of a column is only supported beginning with PostgreSQL version 8.0. For more information, see the manual.
byteacastconversiondatabasemodificationpostgresqlschemasqltext
Use the psycopg.Binary() function to escape the binary data:
>>> db = psycopg.connect("dbname=%s user=%s" % (database, user))
>>> db.autocommit(True)
>>> cursor = db.cursor()
>>> file = "/path/to/binary_file.jpg"
>>> fd = open(file, "r")
>>> contents = fd.read(os.stat(file)[6])
>>> fd.close()
>>> cursor.execute("INSERT INTO pr0n (image) VALUES (%s)", (psycopg.Binary(contents)))
binarybyteacursordbapiescapeinteractivelanguagespostgresqlprogrammingpsycopgpython