import os import tempfile import logging import pyqrcode import time # Created by Francesco Mangiacrapa # francesco.mangiacrapa@isti.cnr.it # ISTI-CNR Pisa (ITALY) CATALINA_HOME = 'CATALINA_HOME' log = logging.getLogger(__name__) temp_dir = None qr_code_dir = None qr_code_dir_name = "qr_code_for_catalogue" class D4S_QrCode(): def __init__(self, qr_code_url=None): self._qr_code_url = qr_code_url global temp_dir if temp_dir is None: D4S_QrCode.init_temp_dir() if temp_dir is None: raise Exception('No temp directory found!') def get_qrcode_path(self): image_name = self._qr_code_url.rsplit('/', 1)[-1] image_name+=".svg" image_path = os.path.join(qr_code_dir, image_name) # ONLY IF QRCODE DOES NOT EXIST THEN IT WILL BE CREATED if not os.path.isfile(image_path): url = pyqrcode.create(self._qr_code_url) url.svg(image_path, scale=3) log.debug("Created QRCode image: " + image_name) attempt = 0 while not os.path.exists(image_path) and attempt < 3: time.sleep(1) attempt += 1 if os.path.isfile(image_path): log.info("QRcode image exists at: " + image_path) else: log.error("%s isn't a file!" % image_path) return image_path @classmethod def init_temp_dir(cls): global temp_dir global qr_code_dir_name global qr_code_dir try: temp_dir = str(os.environ[CATALINA_HOME]) temp_dir = os.path.join(temp_dir, "temp") except KeyError as error: log.error("No environment variable for: %s" % CATALINA_HOME) if temp_dir is None: temp_dir = tempfile.gettempdir() # using system tmp dir log.debug("Temp dir is: %s" % temp_dir) qr_code_dir = os.path.join(temp_dir, qr_code_dir_name) if not os.path.exists(qr_code_dir): os.makedirs(qr_code_dir) def get_temp_directory(self): return temp_dir def get_qr_code_dir(self): return qr_code_dir # D4S_QrCode.init_temp_dir() #qr_code = D4S_QrCode("http://data.d4science.org/ctlg/BiodiversityLab/distribution_of_the_giant_squid_architeuthis") #print qr_code.get_qrcode_path()