· 8 years ago · Aug 13, 2018, 05:32 PM
1"""A tool for saving files to and from a postgresql db.
2"""
3import os
4import sys
5import argparse
6import psycopg2
7
8db_conn_str = "postgresql://word:word@111.11.111.1:5432/DBNAME"
9create_table_stm = """
10CREATE TABLE files (
11 id serial primary key,
12 orig_filename text not null,
13 file_data bytea not null
14)
15"""
16
17check_for_table = """
18IF EXISTS (SELECT * FROM files)
19"""
20
21def main(argv):
22 parser = argparse.ArgumentParser()
23 parser_action = parser.add_mutually_exclusive_group(required=True)
24 parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB")
25 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')
26 parser.add_argument("filename", help="Name of file to write to / fetch from")
27 args = parser.parse_args(argv[1:])
28
29 conn = psycopg2.connect(db_conn_str)
30 curs = conn.cursor()
31
32 # Check if the table already exists
33 if curs.execute(check_for_table) is None:
34
35 # If it DOES NOT exist, create it
36 curs.execute(create_table_stm)
37
38 # If it DOES exist, ??
39 elif
40 if args.store:
41 with open(args.filename,'rb') as f:
42 filedata = psycopg2.Binary(f.read())
43 curs.execute("INSERT INTO files(id, orig_filename, file_data) VALUES (DEFAULT,%s,%s) RETURNING id", (args.filename, filedata))
44 print curs
45 returned_id = curs.fetchone()[0]
46 print("Stored {0} into DB record {1}".format(args.filename, returned_id))
47 conn.commit()
48
49 elif args.fetch is not None:
50 with open(args.filename,'wb') as f:
51 curs.execute("SELECT file_data, orig_filename FROM files WHERE id = %s", (int(args.fetch),))
52 (file_data, orig_filename) = curs.fetchone()
53 f.write(file_data)
54 print("Fetched {0} into file {1}; original filename was {2}".format(args.fetch, args.filename, orig_filename))
55
56 conn.close()
57
58if __name__ == '__main__':
59 main(sys.argv)