Background... I have an almost black box web application appliance that has a postgres DB on the back end Although I have access to a command line, to psql and and to a fairly basic Python 2.7 install, this is fairly limited (no ability to install additional python libs for example - yes, I know I could hack this but there is a contractual as well as practical element to this)
Problem... A table in the DB stores images in bytea format. based on some parameters passed from a browser in an ajax call, I need to extract the image to /tmp
To do this from psql I can do:
\copy (SELECT encode(image, 'hex') FROM images WHERE img_id = (select bin_id from binaries where id = '12345678')) TO '/tmp/12345678.jpg'
So...
Back to Python.
I have no sql libraries but I do have os and subprocess
So normally, to query the db I'd use os to:
something = os.popen(os_str).read()
where os_str is a psql shell command with an SQL statement appended
At the moment my test script looks like:
import os, sys, cgi, cgitb
form = cgi.FieldStorage()
uid = form.getvalue('uid')
if uid is None : # missing user_id
uid = "12345678"
imgType = form.getvalue('imgType')
if imgType is None : # missing imgType
imgType = "png"
imgName = uid + "." + imgType
pg_str = "psql -U xxx yyy -A -t -c "
sql = "???"
os_str = pg_str + "\'" + sql + "\'" + ";"
os.popen(os_str).read()
I'm fairly certain that I'm in quote/escape hell here
I've tried seemingly endless combinations to do
sql = "\copy (SELECT encode(image, 'hex') FROM images WHERE img_id = (select bin_id from binaries where id = '+ uid + "')) TO '/tmp/" + imgName + "'"
Obviously, I know that's wrong, but it seems the simplest way to illustrate what I need
print os_stryields?"\c"happens to be the same asr"\c", but that's not true in general. (Try a command that starts with annand see what happens.)