Esempio n. 1
0
def persist_client_configuration(
    client: "Client", default_team: Optional[str] = None, config_path: Optional[Path] = None
) -> Config:
    """Authenticate user against the server and creates a configuration file for it

    Parameters
    ----------
    client : Client
        Client to take the configurations from
    config_path : Path
        Optional path to specify where to save the configuration file

    Returns
    -------
    Config
    A configuration object to handle YAML files
    """
    if not config_path:
        config_path = Path.home() / ".darwin" / "config.yaml"
        config_path.parent.mkdir(exist_ok=True)

    team_config = client.config.get_default_team()
    config = Config(config_path)
    config.set_team(team=team_config["slug"], api_key=team_config["api_key"], datasets_dir=team_config["datasets_dir"])
    config.set_global(api_endpoint=client.url, base_url=client.base_url, default_team=default_team)

    return config
Esempio n. 2
0
    def from_api_key(cls, api_key: str, datasets_dir: Optional[Path] = None):
        """Factory method to create a client given an API key

        Parameters
        ----------
        api_key: str
            API key to use to authenticate the client
        datasets_dir : str
            String where the client should be initialized from (aka the root path)

        Returns
        -------
        Client
            The inited client
        """
        if datasets_dir is None:
            datasets_dir = Path.home() / ".darwin" / "datasets"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"ApiKey {api_key}"
        }
        api_url = Client.default_api_url()
        response = requests.get(urljoin(api_url, "/users/token_info"),
                                headers=headers)

        if response.status_code != 200:
            raise InvalidLogin()
        data = response.json()
        team_id = data["selected_team"]["id"]
        team = [
            team["slug"] for team in data["teams"] if team["id"] == team_id
        ][0]

        config = Config(path=None)
        config.set_team(team=team,
                        api_key=api_key,
                        datasets_dir=str(datasets_dir))
        config.set_global(api_endpoint=api_url,
                          base_url=Client.default_base_url())

        return cls(config=config, default_team=team)