customerio 3.2.0__tar.gz → 3.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. customerio-3.3.0/.github/workflows/publish.yml +129 -0
  2. customerio-3.3.0/.github/workflows/registry-check.yml +147 -0
  3. customerio-3.3.0/.release-please-manifest.json +3 -0
  4. customerio-3.3.0/CHANGELOG.md +8 -0
  5. customerio-3.3.0/CODEOWNERS +2 -0
  6. {customerio-3.2.0 → customerio-3.3.0}/PKG-INFO +38 -1
  7. {customerio-3.2.0 → customerio-3.3.0}/README.md +37 -0
  8. {customerio-3.2.0 → customerio-3.3.0}/customerio/__init__.py +4 -1
  9. customerio-3.3.0/customerio/client.py +263 -0
  10. {customerio-3.2.0 → customerio-3.3.0}/customerio/client_base.py +21 -1
  11. {customerio-3.2.0 → customerio-3.3.0}/customerio.egg-info/PKG-INFO +38 -1
  12. {customerio-3.2.0 → customerio-3.3.0}/customerio.egg-info/SOURCES.txt +6 -0
  13. {customerio-3.2.0 → customerio-3.3.0}/customerio.egg-info/scm_file_list.json +25 -18
  14. customerio-3.3.0/customerio.egg-info/scm_version.json +8 -0
  15. customerio-3.3.0/release-please-config.json +9 -0
  16. customerio-3.2.0/.github/workflows/publish.yml +0 -37
  17. customerio-3.2.0/customerio.egg-info/scm_version.json +0 -8
  18. {customerio-3.2.0 → customerio-3.3.0}/.github/dependabot.yml +0 -0
  19. {customerio-3.2.0 → customerio-3.3.0}/.github/workflows/main.yml +0 -0
  20. {customerio-3.2.0 → customerio-3.3.0}/.gitignore +0 -0
  21. {customerio-3.2.0 → customerio-3.3.0}/.gitpod.yml +0 -0
  22. {customerio-3.2.0 → customerio-3.3.0}/AUTHORS +0 -0
  23. {customerio-3.2.0 → customerio-3.3.0}/LICENSE +0 -0
  24. {customerio-3.2.0 → customerio-3.3.0}/MANIFEST.in +0 -0
  25. {customerio-3.2.0 → customerio-3.3.0}/Makefile +0 -0
  26. {customerio-3.2.0 → customerio-3.3.0}/customerio/api.py +0 -0
  27. {customerio-3.2.0 → customerio-3.3.0}/customerio/constants.py +0 -0
  28. {customerio-3.2.0 → customerio-3.3.0}/customerio/regions.py +0 -0
  29. {customerio-3.2.0 → customerio-3.3.0}/customerio/track.py +0 -0
  30. {customerio-3.2.0 → customerio-3.3.0}/customerio.egg-info/dependency_links.txt +0 -0
  31. {customerio-3.2.0 → customerio-3.3.0}/customerio.egg-info/requires.txt +0 -0
  32. {customerio-3.2.0 → customerio-3.3.0}/customerio.egg-info/top_level.txt +0 -0
  33. {customerio-3.2.0 → customerio-3.3.0}/pyproject.toml +0 -0
  34. {customerio-3.2.0 → customerio-3.3.0}/requirements.txt +0 -0
  35. {customerio-3.2.0 → customerio-3.3.0}/setup.cfg +0 -0
  36. {customerio-3.2.0 → customerio-3.3.0}/setup.py +0 -0
@@ -0,0 +1,129 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ release:
7
+ types: [published]
8
+
9
+ permissions: {}
10
+
11
+ jobs:
12
+ release-please:
13
+ name: Open or tag a release
14
+ if: github.event_name == 'push'
15
+ runs-on: ubuntu-latest
16
+ permissions:
17
+ contents: write
18
+ pull-requests: write
19
+ # release-please creates its autorelease labels through the Issues API.
20
+ issues: write
21
+ outputs:
22
+ release_created: ${{ steps.release.outputs.release_created }}
23
+ tag_name: ${{ steps.release.outputs.tag_name }}
24
+ sha: ${{ steps.release.outputs.sha }}
25
+ steps:
26
+ - id: release
27
+ uses: googleapis/release-please-action@v5
28
+
29
+ # Publishing lives in this file because PyPI trusted publishing is bound to
30
+ # publish.yml. A release created by release-please with GITHUB_TOKEN does not
31
+ # fire the `release` event, so the push run publishes it here instead.
32
+ publish:
33
+ name: Build and publish
34
+ needs: release-please
35
+ if: ${{ !cancelled() && (github.event_name == 'release' || needs.release-please.outputs.release_created == 'true') }}
36
+ runs-on: ubuntu-latest
37
+ environment: pypi
38
+ permissions:
39
+ contents: read
40
+ id-token: write
41
+ env:
42
+ # Secrets cannot be read in step conditions, so expose it here and test the env var.
43
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_NOTIFY_RELEASES_WEBHOOK_URL }}
44
+ TAG_NAME: ${{ needs.release-please.outputs.tag_name || github.event.release.tag_name }}
45
+ steps:
46
+ # Overlapping pushes can make a later run create an earlier release, so
47
+ # build the tagged commit rather than the commit that triggered this run.
48
+ # Full history because the package version comes from the git tag.
49
+ - uses: actions/checkout@v7
50
+ with:
51
+ fetch-depth: 0
52
+ ref: ${{ needs.release-please.outputs.sha || github.ref }}
53
+
54
+ - name: Set up Python
55
+ uses: actions/setup-python@v7
56
+ with:
57
+ python-version: "3.14"
58
+ cache: pip
59
+ cache-dependency-path: pyproject.toml
60
+
61
+ - name: Install build tools
62
+ run: |
63
+ python -m pip install --upgrade pip
64
+ python -m pip install build
65
+
66
+ - name: Build package
67
+ run: python -m build
68
+
69
+ # A build that cannot see the tag gets a dev version, which must not ship.
70
+ - name: Check the built version matches the tag
71
+ run: |
72
+ # Python rewrites versions, so v3.3.0-rc.1 builds as 3.3.0rc1.
73
+ version=$(python -c 'import sys; from packaging.version import Version; print(Version(sys.argv[1]))' "$TAG_NAME")
74
+ if ! ls "dist/customerio-${version}.tar.gz" "dist/customerio-${version}-"*.whl; then
75
+ echo "::error::dist/ does not hold version ${version}"
76
+ ls dist
77
+ exit 1
78
+ fi
79
+
80
+ - name: Publish to PyPI
81
+ uses: pypa/gh-action-pypi-publish@release/v1
82
+
83
+ - name: Notify Slack of published release
84
+ if: ${{ success() && env.SLACK_WEBHOOK_URL != '' }}
85
+ uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0
86
+ continue-on-error: true
87
+ with:
88
+ webhook: ${{ env.SLACK_WEBHOOK_URL }}
89
+ webhook-type: incoming-webhook
90
+ payload: |
91
+ {
92
+ "text": "Python SDK ${{ env.TAG_NAME }} published to PyPI",
93
+ "username": "Python deployment bot",
94
+ "icon_url": "https://raw.githubusercontent.com/github/explore/main/topics/python/python.png",
95
+ "channel": "#server-sdk-deployments",
96
+ "blocks": [
97
+ {
98
+ "type": "section",
99
+ "text": {
100
+ "type": "mrkdwn",
101
+ "text": "*Python* SDK ${{ env.TAG_NAME }} published to PyPI. <https://github.com/${{ github.repository }}/releases/tag/${{ env.TAG_NAME }}|View release>"
102
+ }
103
+ }
104
+ ]
105
+ }
106
+
107
+ - name: Notify Slack of failed release
108
+ if: ${{ failure() && env.SLACK_WEBHOOK_URL != '' }}
109
+ uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0
110
+ continue-on-error: true
111
+ with:
112
+ webhook: ${{ env.SLACK_WEBHOOK_URL }}
113
+ webhook-type: incoming-webhook
114
+ payload: |
115
+ {
116
+ "text": "Python SDK release failure",
117
+ "username": "Python deployment bot",
118
+ "icon_url": "https://raw.githubusercontent.com/github/explore/main/topics/python/python.png",
119
+ "channel": "#server-sdk-deployments",
120
+ "blocks": [
121
+ {
122
+ "type": "section",
123
+ "text": {
124
+ "type": "mrkdwn",
125
+ "text": "*Python* SDK release :warning: failure :warning:\nView the <https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}|CI logs> to see why."
126
+ }
127
+ }
128
+ ]
129
+ }
@@ -0,0 +1,147 @@
1
+ name: Check PyPI release
2
+
3
+ # The publish job waits for an approval, so the wait starts when that workflow
4
+ # finishes, not when the release is published. release-please also creates
5
+ # releases with GITHUB_TOKEN, which fires no `release` event to listen for.
6
+ on:
7
+ workflow_run:
8
+ workflows: [Publish to PyPI]
9
+ types: [completed]
10
+ workflow_dispatch:
11
+ inputs:
12
+ version:
13
+ description: Version to look for on PyPI (use a fake one to test the alert)
14
+ required: true
15
+ type: string
16
+
17
+ permissions:
18
+ contents: read
19
+ # To read the jobs of the publish run.
20
+ actions: read
21
+
22
+ jobs:
23
+ check:
24
+ name: Confirm version is on PyPI
25
+ # Runs after every publish run, failed and cancelled ones too. The release
26
+ # already exists by then, and a failed publish can still have uploaded the
27
+ # package, so the registry is the only way to tell. The tag check below
28
+ # filters out pushes that released nothing.
29
+ runs-on: ubuntu-latest
30
+ timeout-minutes: 60
31
+ env:
32
+ # Secrets cannot be read in step conditions, so expose it here and test the env var.
33
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_NOTIFY_RELEASES_WEBHOOK_URL }}
34
+ PYPI_DIST: customerio
35
+ # Poll every 3 minutes for about 50 minutes.
36
+ MAX_ATTEMPTS: "17"
37
+ SLEEP_SECONDS: "180"
38
+ steps:
39
+ - uses: actions/checkout@v7
40
+ with:
41
+ # Full history so release tags are available.
42
+ fetch-depth: 0
43
+ ref: ${{ github.event.workflow_run.head_sha || github.sha }}
44
+
45
+ - name: Work out which version to look for
46
+ id: version
47
+ env:
48
+ VERSION_INPUT: ${{ inputs.version }}
49
+ PUBLISH_EVENT: ${{ github.event.workflow_run.event }}
50
+ # For a publish run started by a release, head_branch is the release tag.
51
+ RELEASE_TAG: ${{ github.event.workflow_run.head_branch }}
52
+ RUN_STARTED_AT: ${{ github.event.workflow_run.run_started_at }}
53
+ RUN_ID: ${{ github.event.workflow_run.id }}
54
+ RUN_CONCLUSION: ${{ github.event.workflow_run.conclusion }}
55
+ GH_TOKEN: ${{ github.token }}
56
+ run: |
57
+ check=true
58
+ if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ]; then
59
+ tag="$VERSION_INPUT"
60
+ elif [ "$PUBLISH_EVENT" = "release" ]; then
61
+ tag="$RELEASE_TAG"
62
+ else
63
+ # Most pushes to main release nothing. A run released the nearest tag
64
+ # when its commit carries that tag, or when the release was published
65
+ # while it ran: overlapping pushes can make a later run create an
66
+ # earlier release, so the tag then sits on an ancestor of this commit.
67
+ tag=$(git describe --tags --abbrev=0 --match 'v[0-9]*' HEAD 2>/dev/null || true)
68
+ tagged=""
69
+ published_at=""
70
+ if [ -n "$tag" ]; then
71
+ tagged=$(git rev-parse -q --verify "refs/tags/${tag}^{commit}" || true)
72
+ published_at=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${tag}" --jq .published_at 2>/dev/null || true)
73
+ fi
74
+ # A failed API call prints its error body, so keep only a real timestamp.
75
+ if ! printf '%s' "$published_at" | grep -Eq '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z$'; then
76
+ published_at=""
77
+ fi
78
+ # A run that ended cleanly with its publish job skipped released
79
+ # nothing itself, even when another run has since tagged its commit.
80
+ publish_job=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}/jobs" \
81
+ --jq '.jobs[] | select(.name == "Build and publish") | .conclusion' 2>/dev/null || true)
82
+ if [ "$RUN_CONCLUSION" = "success" ] && [ "$publish_job" = "skipped" ]; then
83
+ check=false
84
+ echo "The publish job was skipped, nothing to check."
85
+ elif [ -n "$tagged" ] && [ "$tagged" = "$(git rev-parse HEAD)" ]; then
86
+ check=true
87
+ elif [ -n "$tagged" ] && [ -n "$published_at" ] && [ ! "$published_at" \< "$RUN_STARTED_AT" ]; then
88
+ check=true
89
+ else
90
+ check=false
91
+ echo "No release was cut at $(git rev-parse --short HEAD), nothing to check."
92
+ fi
93
+ fi
94
+ version="${tag#v}"
95
+ echo "check=$check" >> "$GITHUB_OUTPUT"
96
+ if [ "$check" = "false" ]; then
97
+ exit 0
98
+ fi
99
+ if ! printf '%s' "$version" | grep -Eq '^[0-9]+(\.[0-9A-Za-z]+)*([-+][0-9A-Za-z.-]+)?$'; then
100
+ echo "::error::'$tag' is not a valid version"
101
+ exit 1
102
+ fi
103
+ echo "version=$version" >> "$GITHUB_OUTPUT"
104
+
105
+ - name: Wait for the version to appear on PyPI
106
+ if: ${{ steps.version.outputs.check == 'true' }}
107
+ env:
108
+ VERSION: ${{ steps.version.outputs.version }}
109
+ run: |
110
+ url="https://pypi.org/pypi/${PYPI_DIST}/${VERSION}/json"
111
+ for attempt in $(seq 1 "$MAX_ATTEMPTS"); do
112
+ status=$(curl -s -o /dev/null -w '%{http_code}' --max-time 30 "$url" || true)
113
+ echo "attempt $attempt/$MAX_ATTEMPTS: $url returned $status"
114
+ if [ "$status" = "200" ]; then
115
+ echo "${PYPI_DIST} ${VERSION} is on PyPI"
116
+ exit 0
117
+ fi
118
+ if [ "$attempt" -lt "$MAX_ATTEMPTS" ]; then
119
+ sleep "$SLEEP_SECONDS"
120
+ fi
121
+ done
122
+ echo "::error::${PYPI_DIST} ${VERSION} is still missing from PyPI"
123
+ exit 1
124
+
125
+ - name: Alert Slack that the version is missing
126
+ if: ${{ failure() && steps.version.outputs.check != 'false' && env.SLACK_WEBHOOK_URL != '' }}
127
+ uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0
128
+ continue-on-error: true
129
+ with:
130
+ webhook: ${{ env.SLACK_WEBHOOK_URL }}
131
+ webhook-type: incoming-webhook
132
+ payload: |
133
+ {
134
+ "text": "Python SDK missing from PyPI",
135
+ "username": "Python deployment bot",
136
+ "icon_url": "https://raw.githubusercontent.com/github/explore/main/topics/python/python.png",
137
+ "channel": "#server-sdk-deployments",
138
+ "blocks": [
139
+ {
140
+ "type": "section",
141
+ "text": {
142
+ "type": "mrkdwn",
143
+ "text": "*Python* SDK ${{ steps.version.outputs.version || 'release' }} is not on PyPI 50 minutes after the publish workflow finished :warning:\nThe publish workflow ended as ${{ github.event.workflow_run.conclusion || 'not run' }}. View the <https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}|CI logs>."
144
+ }
145
+ }
146
+ ]
147
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "3.3.0"
3
+ }
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## [3.3.0](https://github.com/customerio/customerio-python/compare/v3.2.0...v3.3.0) (2026-11-26)
4
+
5
+
6
+ ### Features
7
+
8
+ * one-key client for the new private key ([#137](https://github.com/customerio/customerio-python/issues/137)) ([b47d2d7](https://github.com/customerio/customerio-python/commit/b47d2d7b23ea3b5ab8e703c05ab6a008061b2fbb))
@@ -0,0 +1,2 @@
1
+ # Default owner for everything in this repo
2
+ * @customerio/squad-mobile
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: customerio
3
- Version: 3.2.0
3
+ Version: 3.3.0
4
4
  Summary: Customer.io Python bindings.
5
5
  Author-email: "Peaberry Software Inc." <support@customerio.com>
6
6
  License-Expression: MIT
@@ -64,6 +64,43 @@ cio.track(customer_id="5", name="purchased")
64
64
  cio.track(customer_id="5", name="purchased", data={"price": 23.45})
65
65
  ```
66
66
 
67
+ ### Quick start
68
+
69
+ Create a client with your secret key (`sk_…`). It sends tracking calls to the Track API and transactional messages to the App API, and picks the US or EU region from the key.
70
+
71
+ ```python
72
+ import os
73
+
74
+ from customerio import Client
75
+
76
+ cio = Client(api_key=os.environ["CIO_API_KEY"])
77
+ cio.identify(id="user_123", email="a@example.com")
78
+ cio.track(customer_id="user_123", name="order_completed")
79
+ cio.send_email(
80
+ {
81
+ "to": "a@example.com",
82
+ "identifiers": {"id": "user_123"},
83
+ "transactional_message_id": 5,
84
+ }
85
+ )
86
+ ```
87
+
88
+ Passing `Regions.US` or `Regions.EU` when it disagrees with the key's region raises an error. A custom `Region` is accepted. Legacy App API keys still work for transactional and other App API calls, and default to `Regions.US` unless you pass `region`. Tracking calls send the key as a Bearer token, so on Pipelines workspaces they need a new secret key (`sk_…`) tied to a source.
89
+
90
+ `identify`, `track`, `track_anonymous`, `pageview` and the `send_*` methods are on the client directly. The rest of the Track and App API are on `cio.track_client` and `cio.api_client`.
91
+
92
+ If a call is refused, it raises a `KeyCapabilityError` (a subclass of `CustomerIOException`). A public key (`pk_…`) raises it before any request when you send a transactional message. A 401 or 403 from the server is re-raised as a `KeyCapabilityError` too, chained from the original error. A 401 or 403 can come from the key, its permissions, an IP allowlist or a disabled workspace.
93
+
94
+ ```python
95
+ from customerio import KeyCapabilityError
96
+
97
+ try:
98
+ cio.send_email(request)
99
+ except KeyCapabilityError as e:
100
+ # e.capability == "transactional", e.status_code == 401
101
+ print(e) # The request to send transactional messages was refused (401): ...
102
+ ```
103
+
67
104
  ### Instantiating customer.io object
68
105
 
69
106
  Create an instance of the client with your [Customer.io credentials](https://fly.customer.io/settings/api_credentials).
@@ -32,6 +32,43 @@ cio.track(customer_id="5", name="purchased")
32
32
  cio.track(customer_id="5", name="purchased", data={"price": 23.45})
33
33
  ```
34
34
 
35
+ ### Quick start
36
+
37
+ Create a client with your secret key (`sk_…`). It sends tracking calls to the Track API and transactional messages to the App API, and picks the US or EU region from the key.
38
+
39
+ ```python
40
+ import os
41
+
42
+ from customerio import Client
43
+
44
+ cio = Client(api_key=os.environ["CIO_API_KEY"])
45
+ cio.identify(id="user_123", email="a@example.com")
46
+ cio.track(customer_id="user_123", name="order_completed")
47
+ cio.send_email(
48
+ {
49
+ "to": "a@example.com",
50
+ "identifiers": {"id": "user_123"},
51
+ "transactional_message_id": 5,
52
+ }
53
+ )
54
+ ```
55
+
56
+ Passing `Regions.US` or `Regions.EU` when it disagrees with the key's region raises an error. A custom `Region` is accepted. Legacy App API keys still work for transactional and other App API calls, and default to `Regions.US` unless you pass `region`. Tracking calls send the key as a Bearer token, so on Pipelines workspaces they need a new secret key (`sk_…`) tied to a source.
57
+
58
+ `identify`, `track`, `track_anonymous`, `pageview` and the `send_*` methods are on the client directly. The rest of the Track and App API are on `cio.track_client` and `cio.api_client`.
59
+
60
+ If a call is refused, it raises a `KeyCapabilityError` (a subclass of `CustomerIOException`). A public key (`pk_…`) raises it before any request when you send a transactional message. A 401 or 403 from the server is re-raised as a `KeyCapabilityError` too, chained from the original error. A 401 or 403 can come from the key, its permissions, an IP allowlist or a disabled workspace.
61
+
62
+ ```python
63
+ from customerio import KeyCapabilityError
64
+
65
+ try:
66
+ cio.send_email(request)
67
+ except KeyCapabilityError as e:
68
+ # e.capability == "transactional", e.status_code == 401
69
+ print(e) # The request to send transactional messages was refused (401): ...
70
+ ```
71
+
35
72
  ### Instantiating customer.io object
36
73
 
37
74
  Create an instance of the client with your [Customer.io credentials](https://fly.customer.io/settings/api_credentials).
@@ -7,14 +7,17 @@ from customerio.api import (
7
7
  SendSMSRequest,
8
8
  SendWhatsAppRequest,
9
9
  )
10
- from customerio.client_base import CustomerIOException
10
+ from customerio.client import Client
11
+ from customerio.client_base import CustomerIOException, KeyCapabilityError
11
12
  from customerio.regions import Regions
12
13
  from customerio.track import CustomerIO
13
14
 
14
15
  __all__ = [
15
16
  "APIClient",
17
+ "Client",
16
18
  "CustomerIO",
17
19
  "CustomerIOException",
20
+ "KeyCapabilityError",
18
21
  "Regions",
19
22
  "SendEmailRequest",
20
23
  "SendInAppRequest",
@@ -0,0 +1,263 @@
1
+ """
2
+ Implements a single client for the Track and App APIs, authenticated with one key.
3
+ """
4
+
5
+ import re
6
+ from functools import wraps
7
+ from urllib.parse import urlsplit
8
+
9
+ from requests.auth import AuthBase
10
+
11
+ from .api import APIClient
12
+ from .client_base import CustomerIOException, KeyCapabilityError
13
+ from .regions import Region, Regions
14
+ from .track import CustomerIO
15
+
16
+ # Keys in the shared format look like `{type}_{us|eu}_{random}_{checksum}`, where type
17
+ # is `pk` (public) or `sk` (secret). The server checks the checksum; the client only
18
+ # reads the prefix to pick a host and spot public keys.
19
+ KEY_PREFIX = re.compile(r"^(pk|sk)_(us|eu)_")
20
+
21
+ CAPABILITY_ACTIONS = {
22
+ "track": "send tracking data",
23
+ "transactional": "send transactional messages",
24
+ }
25
+
26
+
27
+ class _BearerAuth(AuthBase):
28
+ """Sends the key as a Bearer token. Set as ``session.auth`` so Requests never swaps
29
+ in Basic auth from a matching ``.netrc`` entry."""
30
+
31
+ def __init__(self, key):
32
+ self.key = key
33
+
34
+ def __call__(self, request):
35
+ request.headers["Authorization"] = f"Bearer {self.key}"
36
+ return request
37
+
38
+
39
+ class _BearerAPIClient(APIClient):
40
+ """App API client that sends the key through :class:`_BearerAuth` as well, so a
41
+ matching ``.netrc`` entry can't replace the header either."""
42
+
43
+ def _build_session(self):
44
+ session = super()._build_session()
45
+ session.auth = _BearerAuth(self.key)
46
+ return session
47
+
48
+
49
+ class _BearerTrackClient(CustomerIO):
50
+ """Track API client that sends the key as a Bearer token instead of Basic auth."""
51
+
52
+ def _build_session(self):
53
+ session = super()._build_session()
54
+ session.auth = _BearerAuth(self.api_key)
55
+ return session
56
+
57
+
58
+ def _guard(capability):
59
+ """Re-raises a 401 or 403 as a KeyCapabilityError so a refusal is never a bare
60
+ auth failure."""
61
+
62
+ def decorator(method):
63
+ @wraps(method)
64
+ def wrapper(*args, **kwargs):
65
+ try:
66
+ return method(*args, **kwargs)
67
+ except KeyCapabilityError:
68
+ raise
69
+ except CustomerIOException as e:
70
+ status = getattr(e, "status_code", None)
71
+ if status not in (401, 403):
72
+ raise
73
+ message = (
74
+ f"The request to {CAPABILITY_ACTIONS[capability]} was refused ({status}): "
75
+ f"{_server_message(e.response)}. Check the key, its permissions, the IP "
76
+ "allowlist and the workspace status."
77
+ )
78
+ raise KeyCapabilityError(capability, message, status_code=status) from e
79
+
80
+ return wrapper
81
+
82
+ return decorator
83
+
84
+
85
+ def _server_message(response):
86
+ # The App API answers {"errors": [{"detail": ...}]}; the Track API uses meta.error.
87
+ try:
88
+ body = response.json()
89
+ if body.get("errors"):
90
+ return body["errors"][0]["detail"]
91
+ return body["meta"]["error"]
92
+ except Exception:
93
+ return response.text
94
+
95
+
96
+ def _require_https(name, url):
97
+ try:
98
+ parts = urlsplit(url)
99
+ # Reading the port is what checks it.
100
+ parts.port # noqa: B018
101
+ except ValueError:
102
+ raise CustomerIOException(f"{name} is not a valid URL") from None
103
+ if parts.scheme != "https":
104
+ raise CustomerIOException(f"{name} must start with https://")
105
+ return parts
106
+
107
+
108
+ class Client:
109
+ """One client for tracking and transactional messages, authenticated with a single key.
110
+
111
+ Tracking methods (``identify``, ``track``, ``track_anonymous``, ``pageview``) go to
112
+ the Track API; ``send_*`` methods go to the App API. Both send the key as a Bearer
113
+ token. For ``sk_us_…`` / ``sk_eu_…`` keys the region comes from the key: passing the
114
+ other built-in region (``Regions.US`` or ``Regions.EU``) raises, and a custom
115
+ ``Region`` is accepted. Legacy keys default to ``Regions.US``.
116
+
117
+ When a call is refused, the method raises a
118
+ :class:`KeyCapabilityError`: before the request when the key's type says so (a
119
+ public ``pk_`` key can't send transactional messages), otherwise when the server
120
+ answers 401 or 403.
121
+
122
+ Other Track and App API methods are on ``track_client`` and ``api_client``.
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ api_key,
128
+ region=None,
129
+ track_url=None,
130
+ api_url=None,
131
+ retries=3,
132
+ timeout=10,
133
+ backoff_factor=0.02,
134
+ use_connection_pooling=True,
135
+ ):
136
+ # A key read from a file often ends in a newline, which Requests rejects and
137
+ # then copies, key included, into the exception message.
138
+ api_key = api_key.strip() if isinstance(api_key, str) else api_key
139
+ if not api_key:
140
+ raise CustomerIOException("api_key is required")
141
+ if region is not None and not isinstance(region, Region):
142
+ raise CustomerIOException("invalid region provided")
143
+
144
+ match = KEY_PREFIX.match(api_key)
145
+ self._key_kind = match.group(1) if match else "legacy"
146
+ key_region = (Regions.EU if match.group(2) == "eu" else Regions.US) if match else None
147
+ # A prefixed key belongs to one region, so a different built-in one can only fail.
148
+ # A custom Region (a proxy or test server) is left alone.
149
+ if key_region and region in (Regions.US, Regions.EU) and region != key_region:
150
+ raise CustomerIOException(
151
+ f"region {region.name} does not match the {key_region.name} region of this key"
152
+ )
153
+ self.region = region or key_region or Regions.US
154
+
155
+ options = dict(
156
+ retries=retries,
157
+ timeout=timeout,
158
+ backoff_factor=backoff_factor,
159
+ use_connection_pooling=use_connection_pooling,
160
+ )
161
+
162
+ track_host = track_port = track_prefix = None
163
+ if track_url:
164
+ parts = _require_https("track_url", track_url)
165
+ track_host, track_port = parts.hostname, parts.port
166
+ # Requests rejects an IPv6 literal without its brackets.
167
+ if track_host and ":" in track_host:
168
+ track_host = f"[{track_host}]"
169
+ # A bare "/" path falls back to the default /api/v1 prefix.
170
+ track_prefix = parts.path.rstrip("/") or None
171
+
172
+ #: Track API client, authenticated with the key as a Bearer token.
173
+ self.track_client = _BearerTrackClient(
174
+ api_key=api_key,
175
+ host=track_host,
176
+ port=track_port,
177
+ url_prefix=track_prefix,
178
+ region=self.region,
179
+ **options,
180
+ )
181
+ if api_url:
182
+ _require_https("api_url", api_url)
183
+ # The App API client appends paths that start with "/".
184
+ api_url = api_url.rstrip("/")
185
+ self._api_client = _BearerAPIClient(api_key, url=api_url, region=self.region, **options)
186
+
187
+ def __enter__(self):
188
+ return self
189
+
190
+ def __exit__(self, *args):
191
+ self.close()
192
+
193
+ def close(self):
194
+ try:
195
+ self.track_client.close()
196
+ finally:
197
+ self._api_client.close()
198
+
199
+ @property
200
+ def api_client(self):
201
+ """App API client, authenticated with the key.
202
+
203
+ Raises :class:`KeyCapabilityError` if the key is a public ``pk_`` key.
204
+ """
205
+ if self._key_kind == "pk":
206
+ raise KeyCapabilityError(
207
+ "transactional",
208
+ "This key can't use the App API: public keys (pk_) are for tracking only. "
209
+ "Use a secret key (sk_).",
210
+ )
211
+ return self._api_client
212
+
213
+ @_guard("track")
214
+ def identify(self, id, **kwargs):
215
+ """Create or update a person. See :meth:`CustomerIO.identify`."""
216
+ return self.track_client.identify(id, **kwargs)
217
+
218
+ @_guard("track")
219
+ def track(self, customer_id, name, data=None, id=None, timestamp=None):
220
+ """Track an event for a person. See :meth:`CustomerIO.track`."""
221
+ return self.track_client.track(customer_id, name, data=data, id=id, timestamp=timestamp)
222
+
223
+ @_guard("track")
224
+ def track_anonymous(self, anonymous_id, name, data=None, id=None, timestamp=None):
225
+ """Track an event for an anonymous visitor. See :meth:`CustomerIO.track_anonymous`."""
226
+ return self.track_client.track_anonymous(
227
+ anonymous_id, name, data=data, id=id, timestamp=timestamp
228
+ )
229
+
230
+ @_guard("track")
231
+ def pageview(self, customer_id, page, **data):
232
+ """Track a page view for a person. See :meth:`CustomerIO.pageview`."""
233
+ return self.track_client.pageview(customer_id, page, **data)
234
+
235
+ @_guard("transactional")
236
+ def send_email(self, request):
237
+ """Send a transactional email. See :meth:`APIClient.send_email`."""
238
+ return self.api_client.send_email(request)
239
+
240
+ @_guard("transactional")
241
+ def send_push(self, request):
242
+ """Send a transactional push. See :meth:`APIClient.send_push`."""
243
+ return self.api_client.send_push(request)
244
+
245
+ @_guard("transactional")
246
+ def send_sms(self, request):
247
+ """Send a transactional SMS. See :meth:`APIClient.send_sms`."""
248
+ return self.api_client.send_sms(request)
249
+
250
+ @_guard("transactional")
251
+ def send_whatsapp(self, request):
252
+ """Send a transactional WhatsApp message. See :meth:`APIClient.send_whatsapp`."""
253
+ return self.api_client.send_whatsapp(request)
254
+
255
+ @_guard("transactional")
256
+ def send_inbox_message(self, request):
257
+ """Send a transactional inbox message. See :meth:`APIClient.send_inbox_message`."""
258
+ return self.api_client.send_inbox_message(request)
259
+
260
+ @_guard("transactional")
261
+ def send_in_app(self, request):
262
+ """Send a transactional in-app message. See :meth:`APIClient.send_in_app`."""
263
+ return self.api_client.send_in_app(request)
@@ -50,6 +50,23 @@ class CustomerIOException(Exception):
50
50
  pass
51
51
 
52
52
 
53
+ class KeyCapabilityError(CustomerIOException):
54
+ """Raised by :class:`customerio.Client` when a call is refused for its key.
55
+
56
+ Raised before the request when the key's type rules it out (a public ``pk_``
57
+ key can't send transactional messages). Otherwise the server's 401 or 403 is
58
+ re-raised as this error, chained from the original :class:`CustomerIOException`.
59
+
60
+ ``capability`` is ``"track"`` or ``"transactional"``. ``status_code`` is the
61
+ HTTP status when the server refused the request, else ``None``.
62
+ """
63
+
64
+ def __init__(self, capability, message, status_code=None):
65
+ super().__init__(message)
66
+ self.capability = capability
67
+ self.status_code = status_code
68
+
69
+
53
70
  class ClientBase:
54
71
  def __init__(self, retries=3, timeout=10, backoff_factor=0.02, use_connection_pooling=True):
55
72
  self.timeout = timeout
@@ -100,7 +117,10 @@ class ClientBase:
100
117
 
101
118
  result_status = response.status_code
102
119
  if result_status < 200 or result_status >= 300:
103
- raise CustomerIOException(f"{result_status}: {url} {data} {response.text}")
120
+ error = CustomerIOException(f"{result_status}: {url} {data} {response.text}")
121
+ error.status_code = result_status
122
+ error.response = response
123
+ raise error
104
124
  return response
105
125
 
106
126
  except CustomerIOException:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: customerio
3
- Version: 3.2.0
3
+ Version: 3.3.0
4
4
  Summary: Customer.io Python bindings.
5
5
  Author-email: "Peaberry Software Inc." <support@customerio.com>
6
6
  License-Expression: MIT
@@ -64,6 +64,43 @@ cio.track(customer_id="5", name="purchased")
64
64
  cio.track(customer_id="5", name="purchased", data={"price": 23.45})
65
65
  ```
66
66
 
67
+ ### Quick start
68
+
69
+ Create a client with your secret key (`sk_…`). It sends tracking calls to the Track API and transactional messages to the App API, and picks the US or EU region from the key.
70
+
71
+ ```python
72
+ import os
73
+
74
+ from customerio import Client
75
+
76
+ cio = Client(api_key=os.environ["CIO_API_KEY"])
77
+ cio.identify(id="user_123", email="a@example.com")
78
+ cio.track(customer_id="user_123", name="order_completed")
79
+ cio.send_email(
80
+ {
81
+ "to": "a@example.com",
82
+ "identifiers": {"id": "user_123"},
83
+ "transactional_message_id": 5,
84
+ }
85
+ )
86
+ ```
87
+
88
+ Passing `Regions.US` or `Regions.EU` when it disagrees with the key's region raises an error. A custom `Region` is accepted. Legacy App API keys still work for transactional and other App API calls, and default to `Regions.US` unless you pass `region`. Tracking calls send the key as a Bearer token, so on Pipelines workspaces they need a new secret key (`sk_…`) tied to a source.
89
+
90
+ `identify`, `track`, `track_anonymous`, `pageview` and the `send_*` methods are on the client directly. The rest of the Track and App API are on `cio.track_client` and `cio.api_client`.
91
+
92
+ If a call is refused, it raises a `KeyCapabilityError` (a subclass of `CustomerIOException`). A public key (`pk_…`) raises it before any request when you send a transactional message. A 401 or 403 from the server is re-raised as a `KeyCapabilityError` too, chained from the original error. A 401 or 403 can come from the key, its permissions, an IP allowlist or a disabled workspace.
93
+
94
+ ```python
95
+ from customerio import KeyCapabilityError
96
+
97
+ try:
98
+ cio.send_email(request)
99
+ except KeyCapabilityError as e:
100
+ # e.capability == "transactional", e.status_code == 401
101
+ print(e) # The request to send transactional messages was refused (401): ...
102
+ ```
103
+
67
104
  ### Instantiating customer.io object
68
105
 
69
106
  Create an instance of the client with your [Customer.io credentials](https://fly.customer.io/settings/api_credentials).
@@ -1,18 +1,24 @@
1
1
  .gitignore
2
2
  .gitpod.yml
3
+ .release-please-manifest.json
3
4
  AUTHORS
5
+ CHANGELOG.md
6
+ CODEOWNERS
4
7
  LICENSE
5
8
  MANIFEST.in
6
9
  Makefile
7
10
  README.md
8
11
  pyproject.toml
12
+ release-please-config.json
9
13
  requirements.txt
10
14
  setup.py
11
15
  .github/dependabot.yml
12
16
  .github/workflows/main.yml
13
17
  .github/workflows/publish.yml
18
+ .github/workflows/registry-check.yml
14
19
  customerio/__init__.py
15
20
  customerio/api.py
21
+ customerio/client.py
16
22
  customerio/client_base.py
17
23
  customerio/constants.py
18
24
  customerio/regions.py
@@ -1,28 +1,35 @@
1
1
  {
2
2
  "files": [
3
- "requirements.txt",
4
- "MANIFEST.in",
5
- "Makefile",
6
- "setup.py",
7
- "pyproject.toml",
8
- "LICENSE",
9
- "AUTHORS",
10
- "README.md",
11
- ".gitpod.yml",
12
- ".gitignore",
13
3
  ".github/dependabot.yml",
14
4
  ".github/workflows/main.yml",
15
5
  ".github/workflows/publish.yml",
16
- "tests/test_customerio.py",
17
- "tests/server.py",
18
- "tests/test_client_base.py",
19
- "tests/__init__.py",
20
- "tests/test_api.py",
21
- "customerio/track.py",
6
+ ".github/workflows/registry-check.yml",
7
+ ".gitignore",
8
+ ".gitpod.yml",
9
+ ".release-please-manifest.json",
10
+ "AUTHORS",
11
+ "CHANGELOG.md",
12
+ "CODEOWNERS",
13
+ "LICENSE",
14
+ "MANIFEST.in",
15
+ "Makefile",
16
+ "README.md",
22
17
  "customerio/__init__.py",
18
+ "customerio/api.py",
19
+ "customerio/client.py",
23
20
  "customerio/client_base.py",
21
+ "customerio/constants.py",
24
22
  "customerio/regions.py",
25
- "customerio/api.py",
26
- "customerio/constants.py"
23
+ "customerio/track.py",
24
+ "pyproject.toml",
25
+ "release-please-config.json",
26
+ "requirements.txt",
27
+ "setup.py",
28
+ "tests/__init__.py",
29
+ "tests/server.py",
30
+ "tests/test_api.py",
31
+ "tests/test_client.py",
32
+ "tests/test_client_base.py",
33
+ "tests/test_customerio.py"
27
34
  ]
28
35
  }
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "3.3.0",
3
+ "distance": 0,
4
+ "node": "gdb279a760490ec3f4e3fb48ee0c37afb53f4cb2b",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-11-26"
8
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
3
+ "packages": {
4
+ ".": {
5
+ "release-type": "simple",
6
+ "include-component-in-tag": false
7
+ }
8
+ }
9
+ }
@@ -1,37 +0,0 @@
1
- name: Publish to PyPI
2
-
3
- on:
4
- release:
5
- types: [published]
6
-
7
- permissions:
8
- contents: read
9
- id-token: write
10
-
11
- jobs:
12
- publish:
13
- name: Build and publish
14
- runs-on: ubuntu-latest
15
- environment: pypi
16
- steps:
17
- - uses: actions/checkout@v7
18
- with:
19
- fetch-depth: 0
20
-
21
- - name: Set up Python
22
- uses: actions/setup-python@v7
23
- with:
24
- python-version: "3.14"
25
- cache: pip
26
- cache-dependency-path: pyproject.toml
27
-
28
- - name: Install build tools
29
- run: |
30
- python -m pip install --upgrade pip
31
- python -m pip install build
32
-
33
- - name: Build package
34
- run: python -m build
35
-
36
- - name: Publish to PyPI
37
- uses: pypa/gh-action-pypi-publish@release/v1
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "3.2.0",
3
- "distance": 0,
4
- "node": "g8bac9d6406a389e82b62d44698a03ac8146b4e42",
5
- "dirty": false,
6
- "branch": "HEAD",
7
- "node_date": "2026-07-24"
8
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes