From 50c627fbb06ebf21f55ecccb4fbd532ba759c20a Mon Sep 17 00:00:00 2001 From: Sergio Date: Thu, 31 Aug 2017 02:07:26 -0500 Subject: [PATCH] Pickling capabilities for faster start up times. (#252) On a RaspberryPi it's taking 10 seconds to simply run: import escpos.printer This change creates a pickle file that will load 20x faster. The rationale is that the capabilities.json file doesn't change too often. Also changed some imports for PEP8. --- src/escpos/capabilities.py | 47 +++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 8 deletions(-) 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']