Exemplo n.º 1
0
def upload_file(upload_url, upload_fields, filepath, callback=None):
    """Upload a pre-signed file to Cloudsmith."""
    upload_fields = upload_fields.items()
    upload_fields.append(
        ('file', (os.path.basename(filepath), click.open_file(filepath,
                                                              'rb'))))
    encoder = MultipartEncoder(upload_fields)
    monitor = MultipartEncoderMonitor(encoder, callback=callback)

    config = cloudsmith_api.Configuration()
    if config.proxy:
        proxies = {'http': config.proxy, 'https': config.proxy}
    else:
        proxies = None

    headers = {'content-type': monitor.content_type}

    client = get_files_api()
    headers['user-agent'] = client.api_client.user_agent

    resp = requests.post(upload_url,
                         data=monitor,
                         headers=headers,
                         proxies=proxies)

    try:
        resp.raise_for_status()
    except requests.RequestException as exc:
        raise ApiException(resp.status_code,
                           headers=exc.response.headers,
                           body=exc.response.content)
Exemplo n.º 2
0
def upload_file(upload_url, upload_fields, filepath, callback=None):
    """Upload a pre-signed file to Cloudsmith."""
    upload_fields = list(six.iteritems(upload_fields))
    upload_fields.append(
        ("file", (os.path.basename(filepath), click.open_file(filepath, "rb")))
    )
    encoder = MultipartEncoder(upload_fields)
    monitor = MultipartEncoderMonitor(encoder, callback=callback)

    config = cloudsmith_api.Configuration()
    if config.proxy:
        proxies = {"http": config.proxy, "https": config.proxy}
    else:
        proxies = None

    headers = {"content-type": monitor.content_type}

    client = get_files_api()
    headers["user-agent"] = client.api_client.user_agent

    session = create_requests_session()
    resp = session.post(upload_url, data=monitor, headers=headers, proxies=proxies)

    try:
        resp.raise_for_status()
    except requests.RequestException as exc:
        raise ApiException(
            resp.status_code, headers=exc.response.headers, body=exc.response.content
        )
Exemplo n.º 3
0
def initialise_api(debug=False,
                   host=None,
                   key=None,
                   proxy=None,
                   user_agent=None,
                   headers=None):
    """Initialise the API."""
    config = cloudsmith_api.Configuration()
    config.debug = debug
    config.host = host if host else config.host
    config.proxy = proxy if proxy else config.proxy
    config.user_agent = user_agent
    config.headers = headers
    set_api_key(config, key)
    return config
Exemplo n.º 4
0
def get_api_client(cls):
    """Get an API client (with configuration)."""
    config = cloudsmith_api.Configuration()
    client = cls()

    user_agent = getattr(config, 'user_agent', None)
    if user_agent:
        client.api_client.user_agent = user_agent

    headers = getattr(config, 'headers', None)
    if headers:
        for k, v in six.iteritems(headers):
            client.api_client.set_default_header(k, v)

    return client
Exemplo n.º 5
0
def get_user_token(login, password):
    """Retrieve user token from the API (via authentication)."""
    client = get_user_api()

    # Never use API key for the token endpoint
    config = cloudsmith_api.Configuration()
    set_api_key(config, None)

    with catch_raise_api_exception():
        data = client.user_token_create(data={
            'email': login,
            'password': password
        })

    return data.token
Exemplo n.º 6
0
def get_user_token(login, password):
    """Retrieve user token from the API (via authentication)."""
    client = get_user_api()

    # Never use API key for the token endpoint
    config = cloudsmith_api.Configuration()
    set_api_key(config, None)

    with catch_raise_api_exception():
        data, _, headers = client.user_token_create_with_http_info(
            data={
                "email": login,
                "password": password
            })

    ratelimits.maybe_rate_limit(client, headers)
    return data.token
Exemplo n.º 7
0
def service(ctx, opts):
    """Check the status of the Cloudsmith service."""
    click.echo("Retrieving service status ... ", nl=False)

    context_msg = "Failed to retrieve status!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            status, version = get_status(with_version=True)

    click.secho("OK", fg="green")

    config = cloudsmith_api.Configuration()

    click.echo()
    click.echo("The service endpoint is: %(endpoint)s" %
               {"endpoint": click.style(config.host, bold=True)})
    click.echo("The service status is:   %(status)s" %
               {"status": click.style(status, bold=True)})
    click.echo(
        "The service version is:  %(version)s " %
        {"version": click.style(version, bold=True)},
        nl=False,
    )

    api_version = get_api_version_info()

    if semver.compare(version, api_version) > 0:
        click.secho("(maybe out-of-date)", fg="yellow")

        click.echo()
        click.secho(
            "The API library used by this CLI tool is built against "
            "service version: %(version)s" %
            {"version": click.style(api_version, bold=True)},
            fg="yellow",
        )
    else:
        click.secho("(up-to-date)", fg="green")

        click.echo()
        click.secho(
            "The API library used by this CLI tool seems to be up-to-date.",
            fg="green")
Exemplo n.º 8
0
def get_api_client(cls):
    """Get an API client (with configuration)."""
    config = cloudsmith_api.Configuration()
    client = cls()
    client.config = config
    client.api_client.rest_client = RestClient(
        error_retry_cb=getattr(config, "error_retry_cb", None),
        respect_retry_after_header=getattr(config, "rate_limit", True),
    )

    user_agent = getattr(config, "user_agent", None)
    if user_agent:
        client.api_client.user_agent = user_agent

    headers = getattr(config, "headers", None)
    if headers:
        for k, v in six.iteritems(headers):
            client.api_client.set_default_header(k, v)

    return client
Exemplo n.º 9
0
def initialise_api(
    debug=False,
    host=None,
    key=None,
    proxy=None,
    ssl_verify=True,
    user_agent=None,
    headers=None,
    rate_limit=True,
    rate_limit_callback=None,
    error_retry_max=None,
    error_retry_backoff=None,
    error_retry_codes=None,
    error_retry_cb=None,
):
    """Initialise the API."""
    # FIXME: pylint: disable=too-many-arguments
    config = cloudsmith_api.Configuration()
    config.debug = debug
    config.host = host if host else config.host
    config.proxy = proxy if proxy else config.proxy
    config.user_agent = user_agent
    config.headers = headers
    config.rate_limit = rate_limit
    config.rate_limit_callback = rate_limit_callback
    config.error_retry_max = error_retry_max
    config.error_retry_backoff = error_retry_backoff
    config.error_retry_codes = error_retry_codes
    config.error_retry_cb = error_retry_cb
    config.verify_ssl = ssl_verify

    if headers:
        if "Authorization" in config.headers:
            encoded = config.headers["Authorization"].split(" ")[1]
            decoded = base64.b64decode(encoded)
            values = decoded.decode("utf-8")
            config.username, config.password = values.split(":")

    set_api_key(config, key)
    return config
Exemplo n.º 10
0
def check(ctx, opts):
    """Check the status/version of the service."""
    click.echo('Retrieving service status ... ', nl=False)

    context_msg = 'Failed to retrieve status!'
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with spinner():
            status, version = get_status(with_version=True)

    click.secho('OK', fg='green')

    config = cloudsmith_api.Configuration()

    click.echo()
    click.echo('The service endpoint is: %(endpoint)s' %
               {'endpoint': click.style(config.host, bold=True)})
    click.echo('The service status is:   %(status)s' %
               {'status': click.style(status, bold=True)})
    click.echo('The service version is:  %(version)s ' %
               {'version': click.style(version, bold=True)},
               nl=False)

    api_version = get_api_version_info()

    if semver.compare(version, api_version) > 0:
        click.secho('(maybe out-of-date)', fg='yellow')

        click.echo()
        click.secho('The API library used by this CLI tool is built against '
                    'service version: %(version)s' %
                    {'version': click.style(api_version, bold=True)},
                    fg='yellow')
    else:
        click.secho('(up-to-date)', fg='green')

        click.echo()
        click.secho(
            'The API library used by this CLI tool seems to be up-to-date.',
            fg='green')