-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstep1_dump_img_table.py
172 lines (141 loc) · 5.95 KB
/
step1_dump_img_table.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: User
#
# Created: 26-09-2018
# Copyright: (c) User 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
# StdLib
import logging
import argparse
import os
import csv
# Remote libraries
##import sqlite3
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
# local
from common import *# Things like logging setup
def dump_partial_table(connection_string, table_name, csv_filepath, lower_bound=None, upper_bound=None):
"""Export a range from the table to a CSV file"""
logging.debug('dump_partial_table() locals() = {0!r}'.format(locals()))# Record arguments. WARNING: It is dangerous to record connection string!
# Ensure output dir exists
output_dir = os.path.dirname(csv_filepath)
if not os.path.exists(output_dir):
logging.debug('Creating output_dir = {0!r}'.format(output_dir))
os.makedirs(output_dir)
assert(os.path.exists(output_dir))# Make damn sure we have somewhere to put files before we put any load on the DB.
# https://stackoverflow.com/questions/2952366/dump-csv-from-sqlalchemy
Base = automap_base()
engine = create_engine(connection_string, echo=True)# https://docs.sqlalchemy.org/en/latest/core/engines.html#sqlite
Base.prepare(engine, reflect=True)
# Map the tables
Images = Base.classes[table_name]
session = Session(engine, autoflush=False)
if (lower_bound and upper_bound):
# Select the subset between the supplied values.
logging.info('Selecting media in range: {0!r} to {1!r}'.format(lower_bound, upper_bound))
range_images_q = session.query(Images)\
.filter(Images.media >= lower_bound)\
.filter(Images.media <= upper_bound)
elif (upper_bound):
# Select the subset below or equal to upper_bound.
logging.info('Selecting media below {0!r}'.format(upper_bound))
range_images_q = session.query(Images)\
.filter(Images.media <= upper_bound)
elif (lower_bound):
# Select the range above or equal to the lower_bound.
logging.info('Selecting media above {0!r}'.format(lower_bound))
range_images_q = session.query(Images)\
.filter(Images.media >= lower_bound)
else:
# Select everything.
logging.info('Selecting all media')
range_images_q = session.query(Images)
logging.info('len(range_images_q.all()) = {0}'.format(len(range_images_q.all())))# PERFORMANCE This might cause slowdowns, disable outside testing
with open(csv_filepath, 'wb') as csvfile:
outcsv = csv.writer(csvfile, delimiter=',',quotechar='"', quoting = csv.QUOTE_ALL, lineterminator='\n')
# Write header
header = Images.__table__.columns.keys()
outcsv.writerow(header)
# Write records
for record in range_images_q.all():# Write only images in the specified range
outrow = [getattr(record, c) for c in header ]
## print('outrow = {0!r}'.format(outrow))# PERFORMANCE This might cause slowdowns, disable outside testing
outcsv.writerow(outrow)
assert(os.path.exists(csv_filepath))# Be sure an output file was created.
logging.info('Finished dumping table {0} to {1}'.format(table_name, csv_filepath))
return
def dump_table(connection_string, table_name, csv_filepath):
logging.debug('dump_table() args = {0!r}'.format(locals()))# Record arguments !DANGEROUS TO LOG CREDENTIALS!
# https://stackoverflow.com/questions/2952366/dump-csv-from-sqlalchemy
return dump_partial_table(
connection_string,
table_name,
csv_filepath,
lower_bound=None,
upper_bound=None
)
def dev():
"""For development/debugging in IDE/editor without CLI arguments"""
logging.warning('running dev()')
import config
# Dump a table
dump_table(
connection_string=config.CONNECT_STRING,
table_name=config.TABLE_NAME,
csv_filepath=config.CSV_FILEPATH
)
## # Dump a range within a table
## dump_partial_table(
## connection_string=config.CONNECT_STRING,
## table_name=config.TABLE_NAME,
## csv_filepath=config.CSV_FILEPATH,
## lower_bound='1536638719722.webm',
## stop_at=None
## )
logging.warning('exiting dev()')
return
def cli():
"""Command line running"""
# Handle command line args
parser = argparse.ArgumentParser()
parser.add_argument('--connection_string', help='connection_string see https://docs.sqlalchemy.org/en/latest/core/engines.html',# https://docs.sqlalchemy.org/en/latest/core/engines.html
type=str)
parser.add_argument('--table_name', help='table_name, mandatory.',
type=str)
parser.add_argument('--csv_filepath', help='csv_filepath, mandatory.',
type=str)
parser.add_argument('--lower_bound', help='lower_bound, defaults to None',
type=str, default=None)
parser.add_argument('--upper_bound', help='upper_bound, defaults to None',
type=str, default=None)
args = parser.parse_args()
logging.debug('args: {0!r}'.format(args))# Record CLI arguments !DANGEROUS TO LOG CREDENTIALS!
dump_partial_table(
connection_string=args.connection_string,
table_name=args.table_name,
csv_filepath=args.csv_filepath,
lower_bound=args.lower_bound,
upper_bound=None
)
logging.info('exiting cli()')
return
def main():
## dev()
cli()
return
if __name__ == '__main__':
setup_logging(os.path.join("debug", "step1_dump_img_table.log.txt"))# Setup logging
try:
main()
# Log exceptions
except Exception, e:
logging.critical("Unhandled exception!")
logging.exception(e)
logging.info( "Program finished.")