Beispiel #1
0
 def __init__(self, prefixes=None, prompt_func=None, popen=None,
              event_handler=None):
     if not event_handler:
         event_handler = Reporter()
     if not popen:
         popen = RosePopener(event_handler=event_handler)
     self.event_handler = event_handler
     self.popen = popen
     self.prompt_func = prompt_func
     self.prefixes = []
     self.auth_managers = {}
     conf = ResourceLocator.default().get_conf()
     conf_rosie_id = conf.get(["rosie-id"], no_ignore=True)
     if conf_rosie_id is not None:
         for key, node in conf_rosie_id.value.items():
             if node.is_ignored() or not key.startswith("prefix-ws."):
                 continue
             prefix = key.replace("prefix-ws.", "")
             self.auth_managers[prefix] = RosieWSClientAuthManager(
                 prefix, popen=self.popen, prompt_func=self.prompt_func)
     if not prefixes:
         prefixes_str = conf_rosie_id.get_value(["prefixes-ws-default"])
         if prefixes_str:
             prefixes = shlex.split(prefixes_str)
         else:
             prefixes = sorted(self.auth_managers.keys())
     self.set_prefixes(prefixes)
Beispiel #2
0
    def set_prefixes(self, prefixes):
        """Replace the default prefixes.

        Args:
            prefixes (list): List of prefix names as strings.
        """
        prefixes.sort()
        if self.prefixes != prefixes:
            self.prefixes = prefixes
        for prefix in self.prefixes:
            if prefix in self.auth_managers:
                continue
            self.auth_managers[prefix] = RosieWSClientAuthManager(
                prefix,
                popen=self.popen,
                prompt_func=self.prompt_func,
                event_handler=self.event_handler)
        # Remove uncontactable prefixes from the list.
        ok_prefixes = self.hello(return_ok_prefixes=True)
        prefixes = []
        self.unreachable_prefixes = []
        for prefix in self.prefixes:
            if prefix in ok_prefixes:
                prefixes.append(prefix)
            else:
                self.unreachable_prefixes.append(prefix)
        self.prefixes = prefixes
Beispiel #3
0
 def set_prefixes(self, prefixes):
     """Replace the default prefixes."""
     if self.prefixes != prefixes:
         self.prefixes = prefixes
     for prefix in self.prefixes:
         if prefix in self.auth_managers:
             continue
         self.auth_managers[prefix] = RosieWSClientAuthManager(
             prefix, popen=self.popen, prompt_func=self.prompt_func)
Beispiel #4
0
 def __init__(self, prefix=None, popen=None, prompt_func=None):
     if prefix is None:
         prefix = SuiteId.get_prefix_default()
     self.prefix = prefix
     self.auth_manager = RosieWSClientAuthManager(self.prefix, popen=popen, prompt_func=prompt_func)
     self.root = self.auth_manager.root
     self.requests_kwargs = {}
     res_loc = ResourceLocator.default()
     https_ssl_verify_mode_str = (
         res_loc.default().get_conf().get_value(["rosie-id", "prefix-https-ssl-verify." + prefix])
     )
     if https_ssl_verify_mode_str:
         https_ssl_verify_mode = ast.literal_eval(https_ssl_verify_mode_str)
         self.requests_kwargs["verify"] = bool(https_ssl_verify_mode)
     https_ssl_cert_str = res_loc.default().get_conf().get_value(["rosie-id", "prefix-https-ssl-cert." + prefix])
     if https_ssl_cert_str:
         https_ssl_cert = shlex.split(https_ssl_cert_str)
         if len(https_ssl_cert) == 1:
             self.requests_kwargs["cert"] = https_ssl_cert[0]
         else:
             self.requests_kwargs["cert"] = tuple(https_ssl_cert[0:2])
Beispiel #5
0
class RosieWSClient(object):

    """A client for the Rosie web service."""

    def __init__(self, prefix=None, popen=None, prompt_func=None):
        if prefix is None:
            prefix = SuiteId.get_prefix_default()
        self.prefix = prefix
        self.auth_manager = RosieWSClientAuthManager(self.prefix, popen=popen, prompt_func=prompt_func)
        self.root = self.auth_manager.root
        self.requests_kwargs = {}
        res_loc = ResourceLocator.default()
        https_ssl_verify_mode_str = (
            res_loc.default().get_conf().get_value(["rosie-id", "prefix-https-ssl-verify." + prefix])
        )
        if https_ssl_verify_mode_str:
            https_ssl_verify_mode = ast.literal_eval(https_ssl_verify_mode_str)
            self.requests_kwargs["verify"] = bool(https_ssl_verify_mode)
        https_ssl_cert_str = res_loc.default().get_conf().get_value(["rosie-id", "prefix-https-ssl-cert." + prefix])
        if https_ssl_cert_str:
            https_ssl_cert = shlex.split(https_ssl_cert_str)
            if len(https_ssl_cert) == 1:
                self.requests_kwargs["cert"] = https_ssl_cert[0]
            else:
                self.requests_kwargs["cert"] = tuple(https_ssl_cert[0:2])

    def _get(self, method, **kwargs):
        """Send a JSON object to the web server and retrieve results."""
        if method == "address":
            url = kwargs.pop("url").replace("&format=json", "")
        else:
            url = self.root + method
        kwargs["format"] = "json"

        is_retry = False
        while True:
            auth = self.auth_manager.get_auth(is_retry)
            try:
                requests_kwargs = dict(self.requests_kwargs)
                requests_kwargs["params"] = kwargs
                requests_kwargs["auth"] = auth
                response = requests.get(url, **requests_kwargs)
            except requests.exceptions.ConnectionError as exc:
                raise QueryError("%s: %s: %s" % (url, method, str(exc)))
            except requests.exceptions.MissingSchema as exc:
                raise QueryError("URL Error: %s" % (str(exc)))

            if response.status_code != requests.codes["unauthorized"]:  # not 401
                break
            is_retry = True

        try:
            response.raise_for_status()
        except:
            raise QueryError("%s: %s: %s" % (url, kwargs, response.status_code))

        self.auth_manager.store_password()

        try:
            response_url = response.url.replace("&format=json", "")
            return simplejson.loads(response.text), response_url
        except ValueError:
            raise QueryError("%s: %s" % (method, kwargs))

    def get_known_keys(self):
        """Return the known query keys."""
        return self._get("get_known_keys")[0]

    def get_optional_keys(self):
        """Return the optional query keys."""
        return self._get("get_optional_keys")[0]

    def get_query_operators(self):
        """Return the query operators."""
        return self._get("get_query_operators")[0]

    def hello(self):
        """Ask the server to say hello."""
        return self._get("hello")[0]

    def query(self, q, **kwargs):
        """Query the Rosie database."""
        return self._get("query", q=q, **kwargs)

    def search(self, s, **kwargs):
        """Search the Rosie database for a matching string."""
        return self._get("search", s=s, **kwargs)

    def address_search(self, a, **kwargs):
        """Repeat a Rosie query or search by address."""
        return self._get("address", a=a, **kwargs)