forked from trickortweak/flickr-uploader
-
Notifications
You must be signed in to change notification settings - Fork 5
/
uploadr.py
executable file
·703 lines (619 loc) · 29.3 KB
/
uploadr.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
#!/usr/bin/env python
"""
by oPromessa, 2017, 2018
Published on https://github.com/oPromessa/flickr-uploader/
## LICENSE.txt
--------------
* Check usage and licensing notice on LICENSE.txt file.
* PLEASE REVIEW THE SOURCE CODE TO MAKE SURE IT WILL WORK FOR YOUR NEEDS.
## CONTRIBUTIONS ARE WELCOME!
-----------------------------
* Check CONTRIBUTING and TODO files
* FEEDBACK ON ANY TESTING AND FEEDBACK YOU DO IS GREATLY APPRECIATED.
* IF YOU FIND A BUG, PLEASE REPORT IT.
## Recognition
--------------
Inspired by:
* https://github.com/sybrenstuvel/flickrapi
* http://micampe.it/things/flickruploadr
* https://github.com/joelmx/flickrUploadr/
## README.md
------------
* Check README.md file for information including:
### Description
### Features
### Requirements
### Setup on Synology
### Configuration
### Usage/Arguments/Options
### Task Scheduler (cron)
### Recognition
### Final remarks
### Q&A
"""
# =============================================================================
# Import section for Python 2 and 3 compatible code
# from __future__ import absolute_import, division, print_function,
# unicode_literals
from __future__ import division # This way: 3 / 2 == 1.5; 3 // 2 == 1
# =============================================================================
# Import section
import sys
import traceback
import logging
import logging.handlers
import argparse
import os
import os.path
try:
# Use portalocker if available. Required for Windows systems
import portalocker as FileLocker # noqa
FILELOCK = FileLocker.lock
except ImportError:
# Use fcntl
import fcntl as FileLocker
FILELOCK = FileLocker.lockf
import errno
import pprint
# -----------------------------------------------------------------------------
# Helper FlickrUploadr class to upload pics/videos into Flickr.
import lib.FlickrUploadr as FlickrUploadr
# -----------------------------------------------------------------------------
# Helper class and functions for UPLoaDeR Global Constants.
import lib.Konstants as KonstantsClass
# -----------------------------------------------------------------------------
# Helper class and functions to print messages.
import lib.NicePrint as NicePrint
# -----------------------------------------------------------------------------
# Helper class and functions to load, process and verify INI configuration.
import lib.MyConfig as MyConfig
# -----------------------------------------------------------------------------
# Helper class to allow multiprocessing looging into a single file
import lib.multiprocessing_logging as multiprocessing_logging
# =============================================================================
# Logging init code
#
# Getting definitions from Konstants
UPLDR_K = KonstantsClass.Konstants()
# Sets LOGGING_LEVEL to allow logging even if everything else is wrong!
# Parent logger is set to Maximum (DEBUG) so that suns will log as appropriate
# Produces too much ouput info on MyConfig. Setting it to WARNING
logging.getLogger().setLevel(logging.DEBUG)
# define a Handler which writes WARNING messages or higher to the sys.stderr
CONSOLE_LOGGING = logging.StreamHandler()
CONSOLE_LOGGING.setLevel(logging.WARNING)
CONSOLE_LOGGING.setFormatter(logging.Formatter(
fmt=UPLDR_K.Pur + '[' + str(UPLDR_K.Run) + ']' +
'[%(asctime)s]:[%(processName)-11s]' + UPLDR_K.Std +
'[%(levelname)-8s]:[%(name)s] %(message)s',
datefmt=UPLDR_K.TimeFormat))
logging.getLogger().addHandler(CONSOLE_LOGGING)
# Inits with default configuration value, namely LOGGING_LEVEL
MY_CFG = MyConfig.MyConfig()
# Update console logging level as per LOGGING_LEVEL from default config
CONSOLE_LOGGING.setLevel(int(MY_CFG.LOGGING_LEVEL))
# -----------------------------------------------------------------------------
# =============================================================================
# Init code
#
# Python version must be greater than 2.7 for this script to run
#
if sys.version_info < (2, 7):
logging.critical('----------- (V%s) Error Init -----------(Log:%s)'
'This script requires Python 2.7 or newer.'
'Current Python version: [%s] '
'Exiting...',
UPLDR_K.Version,
MY_CFG.LOGGING_LEVEL,
sys.version)
sys.exit(1)
else:
logging.warning('----------- (V%s) Init -----------(Log:%s)'
'Python version on this system: [%s]',
UPLDR_K.Version,
MY_CFG.LOGGING_LEVEL,
sys.version)
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
def my_excepthook(exc_class, exc_value, exc_tb):
""" my_excepthook
Exception handler to be installed over sys.excepthook to allow
traceback reporting information to be reported back to logging file
"""
logging.critical('Exception: %s: %s', exc_class, exc_value)
logging.critical('%s', ''.join(traceback.format_tb(exc_tb)))
# -----------------------------------------------------------------------------
# parse_arguments
#
# This is the main method
#
def parse_arguments():
""" parse_arguments
Parse arguments and return results.
"""
# Parse args --------------------------------------------------------------
parser = argparse.ArgumentParser(
description='Upload files to Flickr. Uses uploadr.ini as config file.',
epilog='by oPromessa, 2017, 2018'
)
# Configuration related options -------------------------------------------
cgrpparser = parser.add_argument_group('Configuration related options')
cgrpparser.add_argument('-C', '--config-file', action='store',
metavar='filename.ini',
type=str,
help='Optional configuration file. '
'Default is:[{!s}]'
.format(UPLDR_K.ini_file))
cgrpparser.add_argument('-a', '--authenticate', action='store_true',
help='Performs/Verifies authentication with '
'Flickr. To be run on initial setup.'
'Does not run any other option.')
# Verbose related options -------------------------------------------------
vgrpparser = parser.add_argument_group('Verbose and dry-run options')
vgrpparser.add_argument('-v', '--verbose', action='count',
help='Verbose output. Use -vv for more verbosity. '
'See also LOGGING_LEVEL value in INI file.')
vgrpparser.add_argument('-x', '--verbose-progress', action='store_true',
help='Provides progress indicator on each upload. '
'See also LOGGING_LEVEL value in INI file.')
vgrpparser.add_argument('-m', '--mask-sensitive', action='store_true',
help='Masks sensitive data on log files like '
'your pics filenames and set/albums names. '
'(Uses SHA1 hashing algorithm)')
vgrpparser.add_argument('-n', '--dry-run', action='store_true',
help='Dry run. No changes are actually performed.')
# Information related options ---------------------------------------------
igrpparser = parser.add_argument_group('Information options')
igrpparser.add_argument('-i', '--title', action='store',
help='Title for uploaded files. '
'Overwrites title set in INI config file. '
'If not specified and not set in INI file, '
'it uses filename as title (*Recommended).')
igrpparser.add_argument('-e', '--description', action='store',
help='Description for uploaded files'
'Overwrites description set in INI file. ')
igrpparser.add_argument('-t', '--tags', action='store',
help='Space-separated tags for uploaded files. '
'It appends to the tags defined in INI file.')
# used in pics_status function
igrpparser.add_argument('-l', '--list-photos-not-in-set',
metavar='N', type=int,
help='List as many as N photos (with tags) '
'not in set. Maximum listed photos is 500.')
# Processing related options ----------------------------------------------
pgrpparser = parser.add_argument_group('Processing related options')
pgrpparser.add_argument('-r', '--drip-feed', action='store_true',
help='Wait a bit between uploading individual '
'files.')
pgrpparser.add_argument('-p', '--processes',
metavar='P', type=int,
help='Number of photos to upload simultaneously. '
'Number of process to assign pics to sets.')
pgrpparser.add_argument('-u', '--not-is-already-uploaded',
action='store_true',
help='Do not check if file is already uploaded '
'and exists on flickr prior to uploading. '
'Use this option for faster INITIAL upload. '
'Do not use it in subsequent uploads to '
'prevent/recover orphan pics without a set.')
pgrpparser.add_argument('--no-delete-from-flickr',
metavar='nodelete',
type=str,
nargs='?',
const=str(UPLDR_K.no_delete_tag),
help='Do not actually delete pics from flicr.com &'
' mark them with tag:[{!s}]'
.format(UPLDR_K.no_delete_tag))
# run in daemon mode uploading every X seconds
pgrpparser.add_argument('-d', '--daemon', action='store_true',
help='Run forever as a daemon.'
'Uploading every SLEEP_TIME seconds. Please '
'note it only performs '
'upload/raw convert/replace.')
# Bad files related options -----------------------------------------------
# Cater for bad files. files in your Library that flickr does not recognize
bgrpparser = parser.add_argument_group('Handling bad and excluded files')
# -b add files to badfiles table
bgrpparser.add_argument('-b', '--bad-files', action='store_true',
help='Save on database bad files to prevent '
'continuous uploading attempts. Bad files are '
'files in your Library that flickr does not '
'recognize (Error 5) or are too large (Error 8). '
'Check also option -c.')
# -c clears the badfiles table to allow a reset of the list
bgrpparser.add_argument('-c', '--clean-bad-files', action='store_true',
help='Resets the badfiles table/list to allow a '
'new uploading attempt for bad files. Bad files '
'are files in your Library that flickr does not '
'recognize (Error 5) or are too large (Error 8). '
'Check also option -b.')
# -s list the badfiles table
bgrpparser.add_argument('-s', '--list-bad-files', action='store_true',
help='List the badfiles table/list.')
# when you change EXCLUDED_FOLDERS setting
bgrpparser.add_argument('-g', '--remove-excluded',
action='store_true',
help='Remove previously uploaded files, that are '
'now being excluded due to change of the INI '
'file configuration EXCLUDED_FOLDERS.'
'NOTE: Option --remove-ignored was '
'dropped in favor of --remove-excluded.')
# Migration related options -----------------------------------------------
# 2.7.0 Version will add album/setName as one
agrpparser = parser.add_argument_group('Migrate to v2.7.0')
agrpparser.add_argument('--add-albums-migrate', action='store_true',
help='From v2.7.0 onwards, uploadr adds to Flickr '
'an album tag to each pic. '
'This option adds such tag to previously '
'loaded pics. uploadr v2.7.0 will perform '
'automatically such migration upon first run '
'This option is *only* available to re-run '
'it, should it be necessary.')
return parser.parse_args()
# Parse args --------------------------------------------------------------
# -----------------------------------------------------------------------------
# run_uploadr
#
# This is the main method
#
def run_uploadr(args):
""" run_uploadr
args = parameters
"""
# -------------------------------------------------------------------------
# Local Variables
#
# myflick = Class Uploadr (created in the Main code)
def check_files_dir():
""" check_files_dir
Confirms setting MYCFG.FILES_DIR is defined and a valid folder.
Exits from program otherwise.
"""
NPR.niceprint('FILES_DIR: [{!s}]'
.format(NPR.strunicodeout(MY_CFG.FILES_DIR)),
verbosity=1,
logalso=logging.WARNING)
if MY_CFG.FILES_DIR == "":
NPR.niceerror(
caught=True,
caughtprefix='xxx',
caughtcode='630',
caughtmsg='Configure in INI file [normally uploadr.ini] '
'the folder [FILES_DIR] with media to sync with Flickr.',
useniceprint=True)
sys.exit(8)
elif not os.path.isdir(MY_CFG.FILES_DIR):
NPR.niceerror(
caught=True,
caughtprefix='xxx',
caughtcode='631',
caughtmsg='FILES_DIR: [{!s}] is not valid.'
'Use an existant folder in INI file [normally uploadr.ini] '
'with media to sync with Flickr. '
.format(NPR.strunicodeout(MY_CFG.FILES_DIR)),
useniceprint=True)
sys.exit(8)
def check_flickr_key_secret():
""" def check_flickr_key_secret():
Confirms the configuration for api_key and secret is defined.
Exits from program otherwise.
"""
if MY_CFG.FLICKR["api_key"] == "" or MY_CFG.FLICKR["secret"] == "":
NPR.niceerror(
caught=True,
caughtprefix='xxx',
caughtcode='635',
caughtmsg='Please enter an API key and secret in the '
'configuration file [normaly uploadr.ini] (see README).',
useniceprint=True)
sys.exit(9)
def check_token_authenticate():
""" check_token_authenticate
Checks if token is available... if not will authenticate
"""
NPR.niceprint('Checking if token is available... '
'if not will authenticate')
if not myflick.check_token():
# authenticate sys.exits in case of failure
myflick.authenticate()
else:
NPR.niceprint('Token is available.',
logalso=logging.INFO)
# Initial checks
check_files_dir()
check_flickr_key_secret()
# Instantiate class Uploadr. getCachedToken is called on __init__
logging.debug('Instantiating the Main class myflick = Uploadr()')
myflick = FlickrUploadr.Uploadr(MY_CFG, args)
# Setup the database. Clean badfiles entries if asked
myflick.setup_db()
if args.clean_bad_files:
myflick.clean_db_badfiles()
if args.authenticate:
check_token_authenticate()
elif args.daemon:
# Will run in daemon mode every SLEEP_TIME seconds
if myflick.check_token():
NPR.niceprint('Will run in daemon mode every [{!s}] seconds'
'Make sure you have previously authenticated!'
.format(MY_CFG.SLEEP_TIME),
logalso=logging.WARNING)
myflick.run()
else:
NPR.niceerror(
caught=True,
caughtprefix='xxx',
caughtcode='641',
caughtmsg='Not able to connect to Flickr.'
'Make sure you have previously authenticated!',
useniceprint=True)
sys.exit(8)
else:
check_token_authenticate()
if args.add_albums_migrate:
NPR.niceprint('Preparation migration to 2.7.0',
fname='add_albums_tag')
if myflick.add_albums_tag():
NPR.niceprint('Successfully added album tags to pics '
'on upload.',
fname='add_albums_tag')
else:
NPR.niceerror(
caught=True,
caughtprefix='xxx',
caughtcode='642',
caughtmsg='Failed adding album tags to pics uploaded. '
'Please check logs, correct, and retry.',
useniceprint=True)
sys.exit(10)
elif args.list_bad_files:
myflick.list_bad_files()
else:
myflick.remove_useless_sets_table()
myflick.get_flickr_sets()
myflick.upload()
myflick.remove_deleted_media()
if args.remove_excluded:
myflick.remove_excluded_media()
myflick.create_sets()
myflick.pics_status(KonstantsClass.media_count)
# Run Uploadr -------------------------------------------------------------
# -----------------------------------------------------------------------------
# check_base_ini_file
#
# Check if base_dir folder exists and ini_file exists and is a file
#
def check_base_ini_file(base_dir, ini_file):
""" check_base_ini_file
Returns True if base_dir is a directory and ini_file is a regular file.
base_dir = Folder
ini_file = INI File path
"""
logging.info('check_base_ini_file: base_dir=[%s] ini_file=[%s]',
NPR.strunicodeout(base_dir),
NPR.strunicodeout(ini_file))
result_check = True
try:
if not (base_dir == '' or os.path.isdir(base_dir)):
raise OSError('[Errno 2] No such directory:[{!s}]'
.format(NPR.strunicodeout(base_dir)))
elif not os.path.isfile(ini_file):
raise OSError('[Errno 2] No such file:[{!s}]'
.format(NPR.strunicodeout(ini_file)))
else:
result_check = True
except OSError as err:
result_check = False
logging.error(
'No config folder and/or INI file found: %s', str(err))
logging.debug('check_base_ini_file: result=[%s]', result_check)
return result_check
# -----------------------------------------------------------------------------
# logging_close_handlers
#
# Close logging handlers
#
def logging_close_handlers():
""" logging_close_handlers
Close logging handlers
"""
handlers = logging.getLogger().handlers[:]
for handler in handlers:
handler.close()
logging.getLogger().removeHandler(handler)
# =============================================================================
# Global Variables
#
# -----------------------------------------------------------------------------
# Class UPLDReConstants
#
# base_dir = Base configuration directory location
# ini_file = Configuration file
# media_count = Counter of total files to initially upload
# -----------------------------------------------------------------------------
# Base_dir set to os.path.abspat(os.path.dirname(sys.argv[0]))
# INI file config:
# 1. Use --config-file argument option [after PARSED_ARGS]
# 2. If not, os.path.dirname(sys.argv[0])
# 3. If not, os.path.dirname(sys.argv[0]), '..', 'etc', 'uploadr.ini'
# Set appropriate configuration within INI file for support files
UPLDR_K.base_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
UPLDR_K.ini_file = os.path.abspath(os.path.join(UPLDR_K.base_dir,
'uploadr.ini'))
UPLDR_K.etc_ini_file = os.path.abspath(
os.path.join(UPLDR_K.base_dir, os.path.pardir, 'etc', 'uploadr.ini'))
UPLDR_K.media_count = 0
# -----------------------------------------------------------------------------
# Debug folder locations and INI files
logging.debug(' base_dir:[%s]', UPLDR_K.base_dir)
logging.debug(' cwd:[%s]', os.getcwd())
logging.debug('sys.prefix/etc:[%s]', os.path.join(sys.prefix, 'etc'))
logging.debug(' abs(argv[0]):[%s]',
os.path.abspath(os.path.dirname(sys.argv[0])))
logging.debug(' abs(__file__):[%s]',
os.path.abspath(os.path.dirname(__file__)))
logging.debug('argv[0]/../etc:[%s]',
os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),
os.path.pardir,
'etc',
'uploadr.ini')))
logging.debug(' ini_file:[%s]', UPLDR_K.ini_file)
logging.debug(' etc_ini_file:[%s]', UPLDR_K.etc_ini_file)
# -----------------------------------------------------------------------------
# =============================================================================
# Functions aliases
#
# NPR = NicePrint.NicePrint
# -----------------------------------------------------------------------------
NPR = NicePrint.NicePrint()
# -----------------------------------------------------------------------------
# =============================================================================
# Main code
#
NPR.niceprint('----------- (V{!s}) Start -----------(Log:{!s})'
.format(UPLDR_K.Version,
MY_CFG.LOGGING_LEVEL),
logalso=logging.WARNING)
# Install exception handler
sys.excepthook = my_excepthook
if __name__ == "__main__":
# Parse the arguments options
PARSED_ARGS = parse_arguments()
if PARSED_ARGS.no_delete_from_flickr:
logging.warning('Option --no-delete-from-flickr enabled=[%s]',
PARSED_ARGS.no_delete_from_flickr)
# Print/show arguments
NPR.niceprint('Output for arguments(args):\n{!s}'
.format(pprint.pformat(PARSED_ARGS)),
verbosity=3,
logalso=logging.INFO)
# Debug: upload_sleep: Seconds to sleep prior to reattempt a failed upload
logging.info('Upload sleep setting:[%s] seconds', UPLDR_K.upload_sleep)
# Set verbosity level as per -v count
NPR.set_verbosity(PARSED_ARGS.verbose)
NPR.set_mask_sensitivity(PARSED_ARGS.mask_sensitive)
# INI file config (1/3)
# 1. Use --config-file argument option [after PARSED_ARGS]
if PARSED_ARGS.config_file:
if not check_base_ini_file(UPLDR_K.base_dir, PARSED_ARGS.config_file):
NPR.niceerror(caught=True,
caughtprefix='+++',
caughtcode='661',
caughtmsg='Invalid -C argument INI file [{!s}]. '
'Exiting...'.format(UPLDR_K.ini_file),
useniceprint=True)
sys.exit(2)
else:
UPLDR_K.ini_file = PARSED_ARGS.config_file
# INI file config (2/3)
# 2. If not, os.path.dirname(sys.argv[0])
elif not check_base_ini_file(UPLDR_K.base_dir, UPLDR_K.ini_file):
NPR.niceerror(caught=True,
caughtprefix='+++',
caughtcode='662',
caughtmsg='Invalid sys.argv INI file [{!s}].'
' Continuing...'.format(UPLDR_K.ini_file),
useniceprint=True)
# INI file config (3/3)
# 3. If not, os.path.dirname(sys.argv[0]), '../etc/uploadr.ini'
if not check_base_ini_file(UPLDR_K.base_dir, UPLDR_K.etc_ini_file):
NPR.niceerror(caught=True,
caughtprefix='+++',
caughtcode='663',
caughtmsg='Invalid sys.argv/etc INI file [{!s}].'
' Exiting...'.format(UPLDR_K.etc_ini_file),
useniceprint=True)
sys.exit(2)
else:
UPLDR_K.ini_file = UPLDR_K.etc_ini_file
# Source configuration from ini_file
logging.warning('FINAL ini_file:[%s]', UPLDR_K.ini_file)
MY_CFG.readconfig(UPLDR_K.ini_file, ['Config'])
if not (MY_CFG.processconfig() and MY_CFG.verifyconfig()):
NPR.niceerror(caught=True,
caughtprefix='+++',
caughtcode='664',
caughtmsg='Incorrect config INI file [{!s}].'
' Exiting...'.format(UPLDR_K.ini_file),
useniceprint=True)
sys.exit(8)
# Update console logging level as per LOGGING_LEVEL from INI file
CONSOLE_LOGGING.setLevel(MY_CFG.LOGGING_LEVEL)
logging.warning('\n\tCONSOLE_LOGGING.setLevel=[%s] '
'\n\tROTATING_LOGGING.setLevel/enabled?=[%s/%s] '
'\n\tMY_CFG.LOGGING_LEVEL=[%s]',
MY_CFG.LOGGING_LEVEL,
MY_CFG.ROTATING_LOGGING_LEVEL,
MY_CFG.ROTATING_LOGGING,
MY_CFG.LOGGING_LEVEL)
# Rotating LOGGING level to err_file
if MY_CFG.ROTATING_LOGGING:
ROTATING_LOGGING = None
if not os.path.isdir(os.path.dirname(MY_CFG.ROTATING_LOGGING_PATH)):
NPR.niceerror(caught=True,
caughtprefix='+++',
caughtcode='665',
caughtmsg='Invalid ROTATING_LOGGING_PATH config.',
useniceprint=True)
else:
# Define a rotating file Handler which writes DEBUG messages
# or higher to err_file
ROTATING_LOGGING = logging.handlers.RotatingFileHandler(
MY_CFG.ROTATING_LOGGING_PATH,
maxBytes=MY_CFG.ROTATING_LOGGING_FILE_SIZE,
backupCount=MY_CFG.ROTATING_LOGGING_FILE_COUNT)
# Update rotating logging level as per LOGGING_LEVEL from INI file
ROTATING_LOGGING.setLevel(MY_CFG.ROTATING_LOGGING_LEVEL)
ROTATING_LOGGING.setFormatter(logging.Formatter(
fmt='[' + str(UPLDR_K.Run) + ']' +
'[%(asctime)s]:[%(processName)-11s]' +
'[%(levelname)-8s]:[%(name)s] %(message)s',
datefmt=UPLDR_K.TimeFormat))
logging.getLogger().addHandler(ROTATING_LOGGING)
# Allow multiprocessing rotating logging into a single file
# CODING: may not work on Windows
if PARSED_ARGS.processes and PARSED_ARGS.processes > 0:
logging.debug('multiprocessing logging handler: Activating...')
multiprocessing_logging.install_mp_handler()
logging.info('multiprocessing logging handler: Activated.')
logging.warning('----------- (V%s) Init Rotating '
'-----------(Log:%s)\n'
'Python version on this system: [%s]',
UPLDR_K.Version,
MY_CFG.LOGGING_LEVEL,
sys.version)
# Enables mask sensitive data on log files.
if PARSED_ARGS.mask_sensitive:
NPR.niceprint('Mask-Sensitive Argument enabled!',
logalso=logging.DEBUG)
# Patterns to filter defined on UPLDR_K.MaskPatterns
logging.debug('Setting Masking Logging Formatter')
for hnd in logging.root.handlers:
hnd.setFormatter(NicePrint.RedactingFormatter(
hnd.formatter,
UPLDR_K.MaskPatterns))
logging.debug('Masking Logging Formatter is now set!')
logging.debug('Masking Patterns: %s', UPLDR_K.MaskPatterns)
NPR.niceprint('Output for FLICKR Configuration:\n{!s}'
.format(pprint.pformat(MY_CFG.FLICKR)),
verbosity=3,
logalso=logging.INFO)
# Ensure that only one instance of this script is running
try:
# FileLocker is an alias to portalocker (if available) or fcntl
FILELOCK(open(MY_CFG.LOCK_PATH, 'w'),
FileLocker.LOCK_EX | FileLocker.LOCK_NB)
except IOError as err:
if err.errno == errno.EAGAIN:
logging.critical('Script already running.')
sys.exit(-1)
raise
finally:
pass
# Run uploader
run_uploadr(PARSED_ARGS)
NPR.niceprint('----------- (V{!s}) End -----------(Log:{!s})'
.format(UPLDR_K.Version,
MY_CFG.LOGGING_LEVEL),
logalso=logging.WARNING)
logging_close_handlers()