summaryrefslogtreecommitdiff
path: root/examples/binary.py
blob: eaa8f1e7bcc03dd02849ce8b79f3e908740f3099 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# binary.py - working with binary data
#
# Copyright (C) 2001-2004 Federico Di Gregorio  <fog@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.

## put in DSN your DSN string

DSN = 'dbname=test'

## don't modify anything below tis line (except for experimenting)

import sys
import psycopg2

if len(sys.argv) > 1:
    DSN = sys.argv[1]

print "Opening connection using dns:", DSN
conn = psycopg2.connect(DSN)
print "Encoding for this connection is", conn.encoding

curs = conn.cursor()
try:
    curs.execute("CREATE TABLE test_binary (id int4, name text, img bytea)")
except:
    conn.rollback()
    curs.execute("DROP TABLE test_binary")
    curs.execute("CREATE TABLE test_binary (id int4, name text, img bytea)")
conn.commit()

# first we try two inserts, one with an explicit Binary call and the other
# using a buffer on a file object.

data1 = {'id':1, 'name':'somehackers.jpg',
         'img':psycopg2.Binary(open('somehackers.jpg').read())}
data2 = {'id':2, 'name':'whereareyou.jpg',
         'img':buffer(open('whereareyou.jpg').read())}

curs.execute("""INSERT INTO test_binary
                  VALUES (%(id)s, %(name)s, %(img)s)""", data1)
curs.execute("""INSERT INTO test_binary
                  VALUES (%(id)s, %(name)s, %(img)s)""", data2)

# now we try to extract the images as simple text strings

print "Extracting the images as strings..."
curs.execute("SELECT * FROM test_binary")

for row in curs.fetchall():
    name, ext = row[1].split('.')
    new_name = name + '_S.' + ext
    print "  writing %s to %s ..." % (name+'.'+ext, new_name),
    open(new_name, 'wb').write(row[2])
    print "done"
    print "  python type of image data is", type(row[2])
    
# extract exactly the same data but using a binary cursor

print "Extracting the images using a binary cursor:"

curs.execute("""DECLARE zot CURSOR FOR
                  SELECT img, name FROM test_binary FOR READ ONLY""")
curs.execute("""FETCH ALL FROM zot""")

for row in curs.fetchall():
    name, ext = row[1].split('.')
    new_name = name + '_B.' + ext
    print "  writing %s to %s ..." % (name+'.'+ext, new_name),
    open(new_name, 'wb').write(row[0])
    print "done"
    print "  python type of image data is", type(row[0])
    
# this rollback is requires because we can't drop a table with a binary cusor
# declared and still open
conn.rollback()

curs.execute("DROP TABLE test_binary")
conn.commit()

print "\nNow try to load the new images, to check it worked!"