def get_resource_url(self, name, prefix=""): """Return the full resouce URL """ portal = api.get_portal() portal_url = portal.absolute_url() if not prefix: return "{}/{}".format(portal_url, name) return "{}/++resource++{}/{}".format(portal_url, prefix, name)
def get_image_resource(self, name, prefix="bika.lims.images"): """Return the full image resouce URL """ portal = api.get_portal() portal_url = portal.absolute_url() if not prefix: return "{}/{}".format(portal_url, name) return "{}/++resource++{}/{}".format(portal_url, prefix, name)
def get_brain_by_uid(self, uid): """Lookup brain in the UID catalog """ if uid == "0": return api.get_portal() uid_catalog = api.get_tool("uid_catalog") results = uid_catalog({"UID": uid}) if len(results) != 1: raise ValueError("Failed to get brain by UID") return results[0]
def __call__(self): protect.CheckAuthenticator(self.request.form) self.portal = api.get_portal() self.request.set('disable_plone.rightcolumn', 1) self.request.set('disable_border', 1) # Handle form submit form = self.request.form if not form.get("dataform", False): return self.template() domain_name = form.get("domain_name", None) # Handle "Clear this Storage" action if form.get("clear_storage", False): del self.storage[domain_name] delete_soup(self.portal, domain_name) message = _("Cleared Storage {}".format(domain_name)) self.add_status_message(message, "info") return self.template() # Get the necessary data for the domain storage = self.get_storage(domain_name) credentials = storage["credentials"] config = storage["configuration"] # Handle "Import" action if form.get("import", False): step = ImportStep(credentials, config) # Handle "Update" action else: fetch_time = form.get("mod_date_limit", None) or \ storage.get("last_fetch_time", None) if not fetch_time: message = 'Cannot get last fetched time, please re-run ' \ 'the Fetch step.' self.add_status_message(message, "error") return self.template() if isinstance(fetch_time, str): try: fetch_time = DateTime(fetch_time) except: message = 'Please enter a valid Date & Time' self.add_status_message(message, "error") return self.template() step = UpdateStep(credentials, config, fetch_time) step.run() return self.template()
def to_localized_time(self, date, **kw): """Converts the given date to a localized time string """ if date is None: return "" # default options options = { "long_format": True, "time_only": False, "context": api.get_portal(), "request": api.get_request(), "domain": "senaite.core", } options.update(kw) return ulocalized_time(date, **options)
def __init__(self, thing): self.data = dict() self.__empty_marker = object if api.is_uid(thing): return self.init_with_uid(thing) if api.is_brain(thing): return self.init_with_brain(thing) if api.is_object(thing): return self.init_with_instance(thing) if thing == "0": return self.init_with_instance(api.get_portal()) raise TypeError("Can not initialize a SuperModel with '{}'".format( repr(thing)))
def get_settings_from_interface(iface): """Get the configuration settings associated to a list of schema interfaces :param iface: The schema interface from which we want to get its fields :return: Dictionary with iface name as key and as value a dictionary with the setting names (keys) linked to that schema and its values. """ settings = {} schema_id = iface.getName() settings[schema_id] = {} schema = getAdapter(api.get_portal(), iface) for setting in getFieldNames(iface): value = getattr(schema, setting, None) if is_json_serializable(value): settings[schema_id][setting] = value return settings
def _set_settings(self, key, data): """Set settings by key """ # Get the Schema interface of the settings being imported ischemas = CONTROLPANEL_INTERFACE_MAPPING.get(key) if not ischemas: return for ischema_name in data.keys(): ischema = None for candidate_schema in ischemas: if candidate_schema.getName() == ischema_name: ischema = candidate_schema schema = getAdapter(api.get_portal(), ischema) # Once we have the schema set the data schema_import_data = data.get(ischema_name) for schema_field in schema_import_data: if schema_import_data[schema_field]: self._set_attr_from_json(schema, schema_field, schema_import_data[schema_field])
def url_fetcher(self, url): """Fetches internal URLs by path and not via an external request. N.B. Multiple calls to this method might exhaust the available threads of the server, which causes a hanging instance. """ if url.startswith("data"): logger.info("Data URL, delegate to default URL fetcher...") return default_url_fetcher(url) logger.info("Fetching URL '{}' for WeasyPrint".format(url)) # get the pyhsical path from the URL request = api.get_request() host = request.get_header("HOST") path = "/".join(request.physicalPathFromURL(url)) # fetch the object by sub-request portal = api.get_portal() context = portal.restrictedTraverse(path, None) if context is None or host not in url: logger.info("External URL, delegate to default URL fetcher...") return default_url_fetcher(url) logger.info("Local URL, fetching data by path '{}'".format(path)) # get the data via an authenticated subrequest response = subrequest(path) # Prepare the return data as required by WeasyPrint string = response.getBody() filename = url.split("/")[-1] mime_type = mimetypes.guess_type(url)[0] redirected_url = url return { "string": string, "filename": filename, "mime_type": mime_type, "redirected_url": redirected_url, }
def get_brain_by_uid(self, uid): """Lookup brain from the right catalog """ if uid == "0": return api.get_portal() # ensure we have the primary catalog if self._catalog is None: uid_catalog = api.get_tool("uid_catalog") results = uid_catalog({"UID": uid}) if len(results) != 1: raise ValueError("No object found for UID '{}'".format(uid)) brain = results[0] self._catalog = self.get_catalog_for(brain) # Fetch the brain with the primary catalog results = self.catalog({"UID": self.uid}) if not results: raise ValueError("No results found for UID '{}'".format(uid)) if len(results) != 1: raise ValueError( "Found more than one object for UID '{}'".format(uid)) return results[0]
def __call__(self): protect.CheckAuthenticator(self.request.form) logger.info("**** AUTO SYNC STARTED ****") self.portal = api.get_portal() storage = u.get_annotation(self.portal)[SYNC_STORAGE] for domain_name, values in storage.iteritems(): # Check if Auto-Sync is enabled for this Remote if not values["configuration"]["auto_sync"]: continue logger.info("Updating data with: '{}' ".format(domain_name)) self.request.form["dataform"] = 1 self.request.form["update"] = 1 self.request.form["domain_name"] = domain_name response = Sync(self.context, self.request) response() logger.info("**** AUTO SYNC FINISHED ****") return "Done..."
def __init__(self, credentials, config): # Soup Handler to interact with the domain's soup table self.sh = None self.session = None self.portal = api.get_portal() # Set Credentials self.domain_name = credentials.get("domain_name", None) self.url = credentials.get("url", None) self.username = credentials.get("ac_name", None) self.password = credentials.get("ac_password", None) self.certificate_file = credentials.get("certificate_file", None) if not any([self.domain_name, self.url, self.username, self.password]): self.fail("Missing parameter in Sync Step: {}".format(credentials)) # Import configuration self.import_settings = config.get("import_settings", False) self.import_users = config.get("import_users", False) self.import_registry = config.get("import_registry", False) # A prefix to be used in object ID's, representing the Remote Instance self.remote_prefix = config.get("remote_prefix", None) # Prefix of this instance in the Remote (if exists) self.local_prefix = config.get("local_prefix", None) # Types to be fully synchronized self.full_sync_types = config.get("full_sync_types", []) # Types to be skipped self.unwanted_content_types = config.get("unwanted_content_types", []) # Types which will not be editable on this instance self.read_only_types = config.get("read_only_types", []) # Types of objects that have been created on this instance and must have # the changes from Remote self.update_only_types = config.get("update_only_types", []) # Types to contain Remote's Prefix in their ID's on this instance self.prefixable_types = config.get("prefixable_types", [])
def get_portal(): """Proxy to senaite.api.get_portal """ return api.get_portal()
def get_annotation(portal): """Annotation storage on the portal object """ if portal is None: portal = api.get_portal() return IAnnotations(portal)
def __init__(self, domain_name): self.domain_name = domain_name self.portal = api.get_portal() self.soup = self._set_soup()
def __call__(self): protect.CheckAuthenticator(self.request.form) self.portal = api.get_portal() self.request.set('disable_plone.rightcolumn', 1) self.request.set('disable_border', 1) # Handle form submit form = self.request.form fetchform = form.get("fetchform", False) dataform = form.get("dataform", False) if not any([fetchform, dataform]): return self.template() # remember the form field values url = form.get("url", "") if not url.startswith("http"): url = "http://{}".format(url) self.url = url self.username = form.get("ac_name", None) self.password = form.get("ac_password", None) # Handle "Import" action if form.get("import", False): domain = form.get("domain", None) self.import_registry_records(domain) self.import_users(domain) self.import_data(domain) logger.info("*** END OF DATA IMPORT {} ***".format(domain)) return self.template() # Handle "Clear this Storage" action if form.get("clear_storage", False): domain = form.get("domain", None) del self.storage[domain] message = _("Cleared Storage {}".format(domain)) self.add_status_message(message, "info") return self.template() # Handle "Clear all Storages" action if form.get("clear", False): self.flush_storage() message = _("Cleared Data Storage") self.add_status_message(message, "info") return self.template() # Handle "Fetch" action if form.get("fetch", False): # check if all mandatory fields have values if not all([self.url, self.username, self.password]): message = _("Please fill in all required fields") self.add_status_message(message, "error") return self.template() # initialize the session self.session = self.get_session(self.username, self.password) # remember the credentials in the storage storage = self.get_storage(self.url) storage["credentials"]["username"] = self.username storage["credentials"]["password"] = self.password # try to get the version of the remote JSON API version = self.get_version() if not version or not version.get('version'): message = _( "Please install senaite.jsonapi on the source system") self.add_status_message(message, "error") return self.template() # try to get the current logged in user user = self.get_authenticated_user() if not user or user.get("authenticated") is False: message = _("Wrong username/password") self.add_status_message(message, "error") return self.template() domain = self.url # Fetch all users from the source self.fetch_users(domain) # Start the fetch process beginning from the portal object self.fetch_data(domain, uid="0") # Fetch registry records that contain the word bika or senaite self.fetch_registry_records(domain, keys=["bika", "senaite"]) logger.info("*** FETCHING DATA FINISHED {} ***".format(domain)) # always render the template return self.template()
def base_url(self): """Portal Base URL """ return api.get_portal().absolute_url()
def update(self): super(SenaiteSetupButtonViewlet, self).update() self.portal = api.get_portal() portal_url = self.portal.absolute_url() self.setup_url = "/".join([portal_url, "@@lims-setup"])
def portal(self): """Return the portal object """ return api.get_portal()
def portal(self): """Returns the Portal Object """ return api.get_portal()
def portal_url(self): return api.get_portal().absolute_url()
def portal(self): return api.get_portal()
def css(self): setup = api.get_portal().bika_setup footer = setup.getResultFooter() context = self.paperformat context.update({"footer": "{}".format(footer.replace("\r\n", "\A"))}) return CSS.substitute(context)
def __call__(self): protect.CheckAuthenticator(self.request.form) self.portal = api.get_portal() self.request.set('disable_plone.rightcolumn', 1) self.request.set('disable_border', 1) # Handle form submit form = self.request.form fetchform = form.get("fetchform", False) if not fetchform: return self.template() self.url = form.get("url", "") if not self.url.startswith("http"): self.url = "https://{}".format(self.url) self.domain_name = form.get("domain_name", None) self.username = form.get("ac_name", None) self.password = form.get("ac_password", None) # check if all mandatory fields have values if not all([self.domain_name, self.url, self.username, self.password]): message = _("Please fill in all required fields") self.add_status_message(message, "error") return self.template() self.auto_sync = (form.get("auto_sync") == 'on') self.import_settings = (form.get("import_settings") == 'on') self.import_users = (form.get("import_users") == 'on') self.import_registry = (form.get("import_registry") == 'on') self.remote_prefix = form.get("remote_prefix", None) self.local_prefix = form.get("local_prefix", None) self.full_sync_types = utils.filter_content_types( form.get("full_sync_types")) self.unwanted_content_types = utils.filter_content_types( form.get("unwanted_content_types")) self.read_only_types = utils.filter_content_types( form.get("read_only_types")) self.update_only_types = utils.filter_content_types( form.get("update_only_types")) self.prefixable_types = utils.filter_content_types( form.get("prefixable_types")) # Prefix Validation if not self.validate_prefix(): return self.template() credentials = dict( url=self.url, domain_name=self.domain_name, ac_name=self.username, ac_password=self.password) config = dict( auto_sync=self.auto_sync, import_settings=self.import_settings, import_users=self.import_users, import_registry=self.import_registry, remote_prefix=self.remote_prefix, local_prefix=self.local_prefix, full_sync_types=self.full_sync_types, unwanted_content_types=self.unwanted_content_types, read_only_types=self.read_only_types, update_only_types=self.update_only_types, prefixable_types=self.prefixable_types, ) fs = FetchStep(credentials, config) verified, message = fs.verify() if verified: fs.run() self.add_status_message(message, "info") else: self.add_status_message(message, "error") # render the template return self.template()
def __init__(self, *args, **kwargs): # needed for template rendering self.context = api.get_portal()