I usually don’t write complete examples of programs for people, but you didn’t require it, and it’s pretty simple, so here you are:
#!/usr/bin/env python3 import os import sys import psycopg2 import argparse db_conn_str = "dbname=regress user=craig" create_table_stm = """ CREATE TABLE files ( id serial primary key, orig_filename text not null, file_data bytea not null ) """ def main(argv): parser = argparse.ArgumentParser() parser_action = parser.add_mutually_exclusive_group(required=True) parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB") parser_action.add_argument("--fetch", type=int, help="Fetch an image from the DB and store it in the named file, overwriting it if it exists. Takes the database file identifier as an argument.", metavar='42') parser.add_argument("filename", help="Name of file to write to / fetch from") args = parser.parse_args(argv[1:]) conn = psycopg2.connect(db_conn_str) curs = conn.cursor()
Written by Python 3.3. Using Python 2.7 requires you to read the file and convert it to a buffer object or use the large functions of the object. Converting to Python 2.6 and later requires installing argparse, possibly other changes.
You want to change the database connection string to something suitable for your system if you are going to test it.
If you are working with large images, consider using psycopg2 large object support instead of bytea - in particular, lo_import for the store, lo_export for writing directly to the file and reading functions of the large object for reading small fragments of the image at a time.
Craig Ringer
source share