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.
This commit is contained in:
parent
99034d0575
commit
50c627fbb0
|
@ -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']
|
||||
|
||||
|
|
Loading…
Reference in New Issue