diff --git a/src/escpos/capabilities.py b/src/escpos/capabilities.py index adebf90..979bfc7 100644 --- a/src/escpos/capabilities.py +++ b/src/escpos/capabilities.py @@ -1,16 +1,47 @@ import re -import six from os import environ, path +import pickle +import logging +import time + +import six import yaml -# Load external printer database -if 'ESCPOS_CAPABILITIES_FILE' in environ: - file_path = environ['ESCPOS_CAPABILITIES_FILE'] -else: - file_path = path.join(path.dirname(__file__), 'capabilities.json') -with open(file_path) as f: - CAPABILITIES = yaml.load(f) +logging.basicConfig() +logger = logging.getLogger(__name__) + + +pickle_dir = environ.get('ESCPOS_CAPABILITIES_PICKLE_DIR', '/tmp/') +pickle_path = path.join(pickle_dir, 'capabilities.pickle') +capabilities_path = environ.get( + 'ESCPOS_CAPABILITIES_FILE', + path.join(path.dirname(__file__), 'capabilities.json')) + +# Load external printer database +t0 = time.time() +logger.debug('Using capabilities from file: %s', capabilities_path) +if path.exists(pickle_path): + if path.getmtime(capabilities_path) > path.getmtime(pickle_path): + logger.debug('Found a more recent capabilities file') + full_load = True + else: + full_load = False + logger.debug('Loading capabilities from pickle in %s', pickle_path) + with open(pickle_path, 'rb') as cf: + CAPABILITIES = pickle.load(cf) +else: + logger.debug('Capabilities pickle file not found: %s', pickle_path) + full_load = True + +if full_load: + logger.debug('Loading and pickling capabilities') + with open(capabilities_path) as cp, open(pickle_path, 'wb') as pp: + CAPABILITIES = yaml.load(cp) + pickle.dump(CAPABILITIES, pp) + +logger.debug('Finished loading capabilities took %.2fs', time.time() - t0) + PROFILES = CAPABILITIES['profiles']