def getTemplates(bikalims_path, restype, filter_by_type=False): """ Returns an array with the Templates available in the Bika LIMS path specified plus the templates from the resources directory specified and available on each additional product (restype). Each array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on, both the template_id and template_title include a prefix that matches with the add-on identifier. template_title is the same name as the id, but with whitespaces and without extension. As an example, for a template from the my.product add-on located in <restype> resource dir, and with a filename "My_cool_report.pt", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} :param bikalims_path: the path inside bika lims to find the stickers. :type bikalims_path: an string as a path :param restype: the resource directory type to search for inside an addon. :type restype: string :param filter_by_type: the folder name to look for inside the templates path :type filter_by_type: string/boolean """ # Retrieve the templates from bika.lims add-on templates_dir = resource_filename("bika.lims", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue directory = templates_resource.directory # Only use the directory asked in 'filter_by_type' if filter_by_type: directory = directory + '/' + filter_by_type if os.path.isdir(directory): dirlist = os.listdir(directory) exts = [ '{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt') ] templates.extend(exts) out = [] templates.sort() for template in templates: title = template[:-3] title = title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return out
def getLayoutsFromResources(_format): layouts = {} for directory in iterDirectoriesOfType(_format.resourceType): layouts.update(getLayoutsFromDirectory(directory, _format)) return layouts
def getLayoutsFromResources(format): layouts = {} for directory in iterDirectoriesOfType(format.resourceType): name = directory.__name__ if directory.isFile(MANIFEST_FILENAME): manifest = directory.openFile(MANIFEST_FILENAME) try: layouts.update(getLayoutsFromManifest(manifest, format, name)) except: logger.exception( "Unable to read manifest for theme directory %s", name) finally: manifest.close() else: # can provide default file for it with no manifest filename = format.defaults.get('file', '') if filename and directory.isFile(filename): _id = name + '/' + filename if _id not in layouts: # not overridden layouts[_id] = { 'title': name.capitalize().replace('-', ' ').replace('.', ' '), 'description': '', 'directory': name, 'file': format.defaults.get('file', '') } return layouts
def getAvailableTemplates(self): """ Returns a DisplayList with the available templates found in browser/templates/samplesprint """ this_dir = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(this_dir, self._TEMPLATES_DIR) tempath = '%s/%s' % (templates_dir, '*.pt') templates = [t.split('/')[-1] for t in glob.glob(tempath)] out = [] for template in templates: out.append({'id': template, 'title': template[:-3]}) for templates_resource in iterDirectoriesOfType( self._TEMPLATES_ADDON_DIR): prefix = templates_resource.__name__ templates = [ tpl for tpl in templates_resource.listDirectory() if tpl.endswith('.pt') ] for template in templates: out.append({ 'id': '{0}:{1}'.format(prefix, template), 'title': '{0} ({1})'.format(template[:-3], prefix), }) return out
def getThemeResources(format, defaults=None, filter=None, manifestFilename=MANIFEST_FILENAME): resources = [] for directory in iterDirectoriesOfType(format.resourceType, filter_duplicates=False): if filter is not None and not filter(directory): continue name = directory.__name__ if directory.isFile(manifestFilename): manifest = directory.openFile(manifestFilename) try: theme = getManifest(manifest, format, defaults) theme['name'] = name resources.append(theme) except: LOGGER.exception( "Unable to read manifest for theme directory %s", name) finally: manifest.close() return resources
def getTemplates(bikalims_path, restype, filter_by_type=False): """ Returns an array with the Templates available in the Bika LIMS path specified plus the templates from the resources directory specified and available on each additional product (restype). Each array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on, both the template_id and template_title include a prefix that matches with the add-on identifier. template_title is the same name as the id, but with whitespaces and without extension. As an example, for a template from the my.product add-on located in <restype> resource dir, and with a filename "My_cool_report.pt", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} :param bikalims_path: the path inside bika lims to find the stickers. :type bikalims_path: an string as a path :param restype: the resource directory type to search for inside an addon. :type restype: string :param filter_by_type: the folder name to look for inside the templates path :type filter_by_type: string/boolean """ # Retrieve the templates from bika.lims add-on templates_dir = resource_filename("bika.lims", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue directory = templates_resource.directory # Only use the directory asked in 'filter_by_type' if filter_by_type: directory = directory + '/' + filter_by_type if os.path.isdir(directory): dirlist = os.listdir(directory) exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template in templates: title = template[:-3] title = title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return out
def test_iterDirectoriesOfType(self): from plone.resource.utils import iterDirectoriesOfType dirs = list(iterDirectoriesOfType('demo')) self.assertEqual(2, len(dirs)) self.assertTrue(dirs[0].context.aq_base is self.zodb_dir['demo']['foo'].context.aq_base) self.assertTrue(dirs[1].directory == self.global_dir['demo']['manifest-test'].directory)
def resources(self): out = [] for resource in iterDirectoriesOfType(self.type): out.append({ "name": resource.__name__, "path": resource.directory, "contents": resource.listDirectory(), }) return out
def onStartup(event): """Call onDiscovery() on each plugin for each theme on startup """ plugins = getPlugins() for themeDirectory in iterDirectoriesOfType(THEME_RESOURCE_NAME): pluginSettings = getPluginSettings(themeDirectory, plugins) for name, plugin in plugins: plugin.onDiscovery(themeDirectory.__name__, pluginSettings[name], pluginSettings)
def getStickerTemplates(self): """ get the sticker templates """ out = [] for stickers_resource in iterDirectoriesOfType('stickers'): prefix = stickers_resource.__name__ stickers = [stk for stk in stickers_resource.listDirectory() if stk.endswith('.pt')] for sticker in stickers: name ='%s:%s' %(prefix,sticker) out.append([name, name]) return DisplayList(out)
def test_iterDirectoriesOfType_dont_filter_duplicates(self): from plone.resource.utils import iterDirectoriesOfType dirs = list(iterDirectoriesOfType('demo', filter_duplicates=False)) self.assertEqual(4, len(dirs)) self.assertTrue(dirs[0].context.aq_base is self.zodb_dir['demo']['foo'].context.aq_base) self.assertTrue(dirs[1].directory == self.global_dir['demo']['foo'].directory) self.assertTrue(dirs[2].directory == self.global_dir['demo']['manifest-test'].directory) self.assertTrue(dirs[3].directory == self.package_dir.directory)
def test_iterDirectoriesOfType_dont_filter_duplicates(self): from plone.resource.utils import iterDirectoriesOfType dirs = list(iterDirectoriesOfType('demo', filter_duplicates=False)) self.assertEqual(4, len(dirs)) self.assertTrue(dirs[0].context.aq_base is self.zodb_dir['demo']['foo'].context.aq_base) unordered_entries = [ self.global_dir['demo']['foo'].directory, self.global_dir['demo']['manifest-test'].directory ] self.assertIn(dirs[1].directory, unordered_entries) self.assertIn(dirs[2].directory, unordered_entries) self.assertNotEqual(dirs[1].directory, dirs[2].directory) self.assertTrue(dirs[3].directory == self.package_dir.directory)
def get_custom_javascripts(self): """Load custom JavaScript resouces Example: <!-- senaite.impress JS resource directory --> <plone:static directory="js" type="senaite.impress.js" name="MY-CUSTOM-SCRIPTS"/> All JS files in this directory get rendered inline in the publishview """ TYPE = "senaite.impress.js" scripts = [] for resource in iterDirectoriesOfType(TYPE): for fname in resource.listDirectory(): # only consider files if not resource.isFile(fname): continue # only JS files if not os.path.splitext(fname)[-1] == ".js": continue portal_url = self.portal.absolute_url() directory = resource.directory resourcename = resource.__name__ scripts.append({ # XXX Seems like traversal does not work in Plone 4 "url": "{}/++{}++{}/{}".format(portal_url, TYPE, resourcename, fname), "directory": directory, "filepath": os.path.join(directory, fname), "filename": fname, "resourcename": resourcename, "filecontents": resource.readFile(fname), }) return scripts
def getWSTemplates(self): """ Returns a DisplayList with the available templates found in ResourceDirectories where type=='worksheet' and name == 'prefix', so that template IDs are "prefix:filename.pt" """ out = [] for directory in iterDirectoriesOfType(self._TEMPLATES_ADDON_DIR): prefix = directory.__name__ templates = [tpl for tpl in directory.listDirectory() if tpl.endswith('.pt')] for template in templates: out.append({ 'id': '{0}:{1}'.format(prefix, template), 'title': '{0} ({1})'.format(template[:-3], prefix), }) return out
def getARReportTemplates(): p = os.path.join("browser", "analysisrequest", "templates", "reports") templates_dir = resource_filename("bika.lims", p) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] out = [{'id': x, 'title': x} for x in templates] for templates_resource in iterDirectoriesOfType('reports'): prefix = templates_resource.__name__ dirlist = templates_resource.listDirectory() templates = [tpl for tpl in dirlist if tpl.endswith('.pt')] for template in templates: out.append({ 'id': '{0}:{1}'.format(prefix, template), 'title': '{0}:{1}'.format(prefix, template), }) return out
def getTemplates(bikalims_path, restype): """ Returns an array with the Templates available in the Bika LIMS path specified plus the templates from the resources directory specified and available on each additional product (restype). Each array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on, both the template_id and template_title include a prefix that matches with the add-on identifier. template_title is the same name as the id, but with whitespaces and without extension. As an example, for a template from the my.product add-on located in <restype> resource dir, and with a filename "My_cool_report.pt", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} """ # Retrieve the templates from bika.lims add-on #templates_dir = resource_filename("bika.lims", bikalims_path) templates_dir = resource_filename("ace.lims", bikalims_path) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts = [ '{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt') ] templates.extend(exts) out = [] templates.sort() for template in templates: title = template[:-3] title = title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return out
def getStickerTemplates(): """ Returns an array with the sticker templates available. Retrieves the TAL templates saved in templates/stickers folder. Each array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on, both the template_id and template_title include a prefix that matches with the add-on identifier. template_title is the same name as the id, but with whitespaces and without extension. As an example, for a template from the my.product add-on located in templates/stickers, and with a filename "EAN128_default_small.pt", the dictionary will look like: {'id': 'my.product:EAN128_default_small.pt', 'title': 'my.product: EAN128 default small'} """ # Retrieve the templates from bika.lims add-on p = os.path.join("browser", "templates", "stickers") templates_dir = resource_filename("bika.lims", p) tempath = os.path.join(templates_dir, '*.pt') templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType('stickers'): prefix = templates_resource.__name__ if prefix == 'bika.lims': continue dirlist = templates_resource.listDirectory() exts = ['{0}:{1}'.format(prefix, tpl) for tpl in dirlist if tpl.endswith('.pt')] templates.extend(exts) out = [] templates.sort() for template in templates: title = template[:-3] title = title.replace('_', ' ') title = title.replace(':', ': ') out.append({'id': template, 'title': title}) return out
def getAvailableFormats(self): """ Returns the available formats found in templates/reports """ this_dir = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(this_dir, 'templates/reports') tempath = '%s/%s' % (templates_dir, '*.pt') templates = [t.split('/')[-1] for t in glob.glob(tempath)] out = [] for template in templates: out.append({'id': template, 'title': template[:-3]}) for templates_resource in iterDirectoriesOfType('reports'): prefix = templates_resource.__name__ templates = [tpl for tpl in templates_resource.listDirectory() if tpl.endswith('.pt')] for template in templates: out.append({ 'id': '{0}:{1}'.format(prefix, template), 'title': '{0} ({1})'.format(template[:-3], prefix), }) return out
def getTemplates(bikalims_path, restype): """ Returns an array with the Templates available in the Bika LIMS path specified plus the templates from the resources directory specified and available on each additional product (restype). Each array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika.lims add-on, both the template_id and template_title include a prefix that matches with the add-on identifier. template_title is the same name as the id, but with whitespaces and without extension. As an example, for a template from the my.product add-on located in <restype> resource dir, and with a filename "My_cool_report.pt", the dictionary will look like: {'id': 'my.product:My_cool_report.pt', 'title': 'my.product: My cool report'} """ # Retrieve the templates from bika.lims add-on templates_dir = resource_filename("bika.lims", bikalims_path) tempath = os.path.join(templates_dir, "*.pt") templates = [os.path.split(x)[-1] for x in glob.glob(tempath)] # Retrieve the templates from other add-ons for templates_resource in iterDirectoriesOfType(restype): prefix = templates_resource.__name__ if prefix == "bika.lims": continue dirlist = templates_resource.listDirectory() exts = ["{0}:{1}".format(prefix, tpl) for tpl in dirlist if tpl.endswith(".pt")] templates.extend(exts) out = [] templates.sort() for template in templates: title = template[:-3] title = title.replace("_", " ") title = title.replace(":", ": ") out.append({"id": template, "title": title}) return out
def getAllResources(format, defaults=None, filter=None, manifestFilename=MANIFEST_FILENAME): """Get a dict of all resources of the resource type indicated by the manifest format. Returns a dict where the keys are the resource ids and the values are manifests. The value may be None if no manifest was found. Pass ``defaults`` to override the defaults from the manifest format. Pass ``filter``, a callable that takes a resource directory as its only argument, if you want to be able to filter out any resource directories. It should return True if the given directory should be included. Pass ``manifestFilename`` to use a different manifest file name convention. """ resources = {} for directory in iterDirectoriesOfType(format.resourceType): if filter is not None and not filter(directory): continue name = directory.__name__ resources[name] = None if directory.isFile(manifestFilename): manifest = directory.openFile(manifestFilename) try: resources[name] = getManifest(manifest, format, defaults) except: LOGGER.exception( "Unable to read manifest for theme directory {0}".format( name ) ) finally: manifest.close() return resources
def getAllResources(format, defaults=None, filter=None, manifestFilename=MANIFEST_FILENAME): """Get a dict of all resources of the resource type indicated by the manifest format. Returns a dict where the keys are the resource ids and the values are manifests. The value may be None if no manifest was found. Pass ``defaults`` to override the defaults from the manifest format. Pass ``filter``, a callable that takes a resource directory as its only argument, if you want to be able to filter out any resource directories. It should return True if the given directory should be included. Pass ``manifestFilename`` to use a different manifest file name convention. """ resources = {} for directory in iterDirectoriesOfType(format.resourceType): if filter is not None and not filter(directory): continue name = directory.__name__ resources[name] = None if directory.isFile(manifestFilename): manifest = directory.openFile(manifestFilename) try: resources[name] = getManifest(manifest, format, defaults) except: LOGGER.exception( "Unable to read manifest for theme directory {0}".format( name)) finally: manifest.close() return resources
def getAvailableFormats(self): """ Returns the available formats found in templates/reports """ this_dir = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(this_dir, 'templates/reports') tempath = '%s/%s' % (templates_dir, '*.pt') templates = [t.split('/')[-1] for t in glob.glob(tempath)] out = [] for template in templates: out.append({'id': template, 'title': template[:-3]}) for templates_resource in iterDirectoriesOfType('reports'): prefix = templates_resource.__name__ templates = [ tpl for tpl in templates_resource.listDirectory() if tpl.endswith('.pt') ] for template in templates: out.append({ 'id': '{0}:{1}'.format(prefix, template), 'title': '{0} ({1})'.format(template[:-3], prefix), }) return out
def getThemeResources(format, defaults=None, filter=None, manifestFilename=MANIFEST_FILENAME): resources = [] for directory in iterDirectoriesOfType(format.resourceType, filter_duplicates=False): if filter is not None and not filter(directory): continue name = directory.__name__ if directory.isFile(manifestFilename): manifest = directory.openFile(manifestFilename) try: theme = getManifest(manifest, format, defaults) theme['name'] = name resources.append(theme) except: LOGGER.exception("Unable to read manifest for theme directory %s", name) finally: manifest.close() return resources