punchrelay 0.1.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.
- punchrelay-0.1.0/.gitignore +8 -0
- punchrelay-0.1.0/LICENSE +21 -0
- punchrelay-0.1.0/PKG-INFO +282 -0
- punchrelay-0.1.0/README.md +259 -0
- punchrelay-0.1.0/pyproject.toml +69 -0
- punchrelay-0.1.0/src/punchrelay/__init__.py +48 -0
- punchrelay-0.1.0/src/punchrelay/_client.py +162 -0
- punchrelay-0.1.0/src/punchrelay/_convert.py +40 -0
- punchrelay-0.1.0/src/punchrelay/_core.py +240 -0
- punchrelay-0.1.0/src/punchrelay/_errors.py +131 -0
- punchrelay-0.1.0/src/punchrelay/_generated/__init__.py +1 -0
- punchrelay-0.1.0/src/punchrelay/_generated/models.py +283 -0
- punchrelay-0.1.0/src/punchrelay/_paging.py +60 -0
- punchrelay-0.1.0/src/punchrelay/_transport.py +194 -0
- punchrelay-0.1.0/src/punchrelay/_version.py +2 -0
- punchrelay-0.1.0/src/punchrelay/models.py +13 -0
- punchrelay-0.1.0/src/punchrelay/py.typed +0 -0
- punchrelay-0.1.0/src/punchrelay/resources/__init__.py +19 -0
- punchrelay-0.1.0/src/punchrelay/resources/attendance.py +220 -0
- punchrelay-0.1.0/src/punchrelay/resources/devices.py +123 -0
- punchrelay-0.1.0/src/punchrelay/resources/locations.py +41 -0
- punchrelay-0.1.0/src/punchrelay/resources/users.py +105 -0
- punchrelay-0.1.0/src/punchrelay/resources/webhooks.py +179 -0
- punchrelay-0.1.0/src/punchrelay/webhooks.py +240 -0
punchrelay-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gravity Technologies
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: punchrelay
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the PunchRelay API: attendance from ZKTeco devices, devices, employees, locations, webhooks and webhook signature verification.
|
|
5
|
+
Author: PunchRelay
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: adms,attendance,punchrelay,webhooks,zkteco
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Framework :: AsyncIO
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: httpx<1,>=0.27
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# PunchRelay Python SDK
|
|
25
|
+
|
|
26
|
+
A client for the PunchRelay API. Use it to read attendance from your ZKTeco devices, manage devices, employees, locations and webhooks, and verify webhook signatures.
|
|
27
|
+
|
|
28
|
+
- Python 3.11 or later
|
|
29
|
+
- Package: `punchrelay`, with a sync client (`PunchRelay`) and an asyncio client (`AsyncPunchRelay`), fully typed
|
|
30
|
+
- One dependency: [httpx](https://www.python-httpx.org/)
|
|
31
|
+
- API reference: `https://<api-host>/docs`
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
pip install punchrelay
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick start
|
|
40
|
+
|
|
41
|
+
Create a key on the dashboard's **API keys** page. Use a `read` key if you only read data, and a `read_write` key if you also make changes. The key tells the API which organisation you are, so no call takes a tenant id.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import os
|
|
45
|
+
from datetime import datetime, timedelta, timezone
|
|
46
|
+
|
|
47
|
+
from punchrelay import PunchRelay
|
|
48
|
+
|
|
49
|
+
with PunchRelay(api_key=os.environ["PUNCHRELAY_API_KEY"], base_url="https://adms.example.com") as client:
|
|
50
|
+
key = client.get_key_info()
|
|
51
|
+
print(f"{key['tenantName']} ({key['scope']})")
|
|
52
|
+
|
|
53
|
+
# Every punch in the last day, newest first. Pages are fetched as you iterate.
|
|
54
|
+
since = datetime.now(timezone.utc) - timedelta(days=1)
|
|
55
|
+
for punch in client.attendance.list_all(from_=since):
|
|
56
|
+
print(punch["punchedAt"], punch["userId"], punch.get("userName"), "@", punch.get("deviceName"))
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Create one client per key and reuse it. It caches the key's organisation after the first call, keeps a connection pool, and is safe to share between threads. Close it when you are done (`client.close()` or a `with` block).
|
|
60
|
+
|
|
61
|
+
### Async
|
|
62
|
+
|
|
63
|
+
`AsyncPunchRelay` has the same options and methods. Await the calls and iterate the `list_all` helpers with `async for`:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from punchrelay import AsyncPunchRelay
|
|
67
|
+
|
|
68
|
+
async with AsyncPunchRelay(api_key=os.environ["PUNCHRELAY_API_KEY"], base_url="https://adms.example.com") as client:
|
|
69
|
+
devices = await client.devices.list()
|
|
70
|
+
async for punch in client.attendance.list_all(from_=since):
|
|
71
|
+
...
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
It runs on asyncio. Concurrent first calls share one key lookup.
|
|
75
|
+
|
|
76
|
+
## What's covered
|
|
77
|
+
|
|
78
|
+
| Area | Methods |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `client.attendance` | `list`, `list_all`, `get`, `get_stats`, `export_csv`, `delete`, `delete_range` |
|
|
81
|
+
| `client.devices` | `list`, `list_models`, `create`, `update`, `delete`, `activate`, `deactivate`, `reboot`, `pull_attendance`, `pull_users`, `queue_command`, `list_commands`, `set_server_address` |
|
|
82
|
+
| `client.users` | `list`, `list_all`, `create`, `bulk_upsert`, `update`, `delete`, `sync`, `sync_one` |
|
|
83
|
+
| `client.locations` | `list`, `create`, `update`, `delete` |
|
|
84
|
+
| `client.webhooks` | `list`, `list_event_types`, `get`, `create`, `update`, `delete`, `rotate_secret`, `enable`, `disable`, `send_test`, `list_deliveries`, `list_all_deliveries`, `get_delivery`, `redeliver` |
|
|
85
|
+
|
|
86
|
+
### Requests and responses are dicts
|
|
87
|
+
|
|
88
|
+
Responses are plain dicts with the API's camelCase keys, exactly as the API sends them. Request bodies are dicts too. Their types are `TypedDict`s in `punchrelay.models` (`AttendanceItem`, `CreateDeviceRequest`, …), so mypy, Pyright and your editor check the keys:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from punchrelay.models import UpsertUserRequest
|
|
92
|
+
|
|
93
|
+
user: UpsertUserRequest = {"pin": "1005", "name": "Ama Mensah"}
|
|
94
|
+
created = client.users.create(user)
|
|
95
|
+
print(created["id"])
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Every key is typed as optional, because the API may add fields. Index the fields you rely on (`punch["userId"]`), or use `.get()` for the nullable ones.
|
|
99
|
+
|
|
100
|
+
Filters and paging are keyword arguments in snake_case: `from_` (with an underscore, because `from` is a Python keyword), `to`, `user_id`, `device_id`, `location_id`, `page`, `page_size`.
|
|
101
|
+
|
|
102
|
+
### Times and dates
|
|
103
|
+
|
|
104
|
+
- **Timestamps** (`from_` and `to` on attendance) accept a timezone-aware `datetime` or an ISO 8601 string. They are sent as UTC. A naive `datetime` raises `ValueError`, because the SDK cannot know which time zone you meant. Responses return timestamps as ISO 8601 strings.
|
|
105
|
+
- **Calendar dates** (`get_stats`, `pull_attendance`) are days in your organisation's time zone. Pass a `date` or `"YYYY-MM-DD"`.
|
|
106
|
+
|
|
107
|
+
### Anything not wrapped yet
|
|
108
|
+
|
|
109
|
+
`client.http` is the underlying [httpx](https://www.python-httpx.org/) client. It uses the same key, retries and errors as the methods above, with paths relative to `base_url`:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
tenant_id = client.get_tenant_id()
|
|
113
|
+
devices = client.http.get(f"/api/tenants/{tenant_id}/devices").json()
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Errors
|
|
117
|
+
|
|
118
|
+
Any non-2xx response raises `PunchRelayError`. It carries:
|
|
119
|
+
|
|
120
|
+
- `status`: the HTTP status
|
|
121
|
+
- `code`: the API's error code, such as `invalid_range` or `forbidden`
|
|
122
|
+
- `message`
|
|
123
|
+
- `body`: the raw response body
|
|
124
|
+
- `retry_after`: seconds, set on a 429
|
|
125
|
+
|
|
126
|
+
When the subscription is suspended (402), the error is a `SubscriptionSuspendedError`. It adds `invoice_number`, `pay_url`, `subscription_status` and `reason`.
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from punchrelay import PunchRelayError, SubscriptionSuspendedError
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
client.devices.reboot(device_id)
|
|
133
|
+
except SubscriptionSuspendedError as err:
|
|
134
|
+
print(f"Suspended: pay {err.invoice_number} at {err.pay_url}")
|
|
135
|
+
except PunchRelayError as err:
|
|
136
|
+
if err.status == 403:
|
|
137
|
+
print("This key is read-only.")
|
|
138
|
+
else:
|
|
139
|
+
raise
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Network failures raise httpx's `httpx.TransportError` subclasses. A call that runs out of time raises `httpx.TimeoutException`.
|
|
143
|
+
|
|
144
|
+
## Retries
|
|
145
|
+
|
|
146
|
+
These failures are retried up to `max_retries` times (default 3), with jittered exponential backoff:
|
|
147
|
+
|
|
148
|
+
- 429 Too Many Requests, on any method. The SDK waits for the server's `Retry-After`.
|
|
149
|
+
- 500, 502, 503 and 504, only on `GET`, `PUT`, `DELETE`, `HEAD` and `OPTIONS`.
|
|
150
|
+
- Network errors, on the same methods.
|
|
151
|
+
|
|
152
|
+
A `POST` is never retried after a 5xx or a network error, because it may already have run on the server.
|
|
153
|
+
|
|
154
|
+
If `Retry-After` is longer than `max_retry_delay` (default 30 s), the SDK raises the 429 immediately instead of waiting. Each key may make 120 requests per minute.
|
|
155
|
+
|
|
156
|
+
## Verifying webhooks
|
|
157
|
+
|
|
158
|
+
`verify_webhook(raw_body, headers, secret)` checks a webhook and returns its event. It does three things:
|
|
159
|
+
|
|
160
|
+
- checks the HMAC-SHA256 signature, using a constant-time comparison (`hmac.compare_digest`)
|
|
161
|
+
- rejects timestamps more than 5 minutes from your clock (change this with `tolerance=`, in seconds)
|
|
162
|
+
- parses the event
|
|
163
|
+
|
|
164
|
+
It raises `WebhookVerificationError` when any check fails.
|
|
165
|
+
|
|
166
|
+
**Pass the raw body, exactly as it was received.** If you parse the JSON and serialise it again, the bytes change and the signature no longer matches. `raw_body` can be `bytes` or `str`. `headers` can be your framework's request headers or a plain dict; names are matched case-insensitively.
|
|
167
|
+
|
|
168
|
+
### Flask
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
import os
|
|
172
|
+
|
|
173
|
+
from flask import Flask, request
|
|
174
|
+
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook
|
|
175
|
+
|
|
176
|
+
app = Flask(__name__)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@app.post("/webhooks/punchrelay")
|
|
180
|
+
def punchrelay_webhook():
|
|
181
|
+
try:
|
|
182
|
+
event = verify_webhook(request.get_data(), request.headers, os.environ["PUNCHRELAY_WEBHOOK_SECRET"])
|
|
183
|
+
except WebhookVerificationError:
|
|
184
|
+
return "", 401
|
|
185
|
+
|
|
186
|
+
if is_attendance_created(event):
|
|
187
|
+
# Queue it for processing. event["id"] stays the same across retries, so de-duplicate on it.
|
|
188
|
+
print(event["data"]["userId"], event["data"]["punchedAt"])
|
|
189
|
+
return "", 204
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Read `request.get_data()` before touching `request.json` or `request.form`.
|
|
193
|
+
|
|
194
|
+
### FastAPI
|
|
195
|
+
|
|
196
|
+
Take the `Request` and read `await request.body()`. Don't declare a Pydantic model for the body, because FastAPI would parse it first.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
import os
|
|
200
|
+
|
|
201
|
+
from fastapi import FastAPI, Request, Response
|
|
202
|
+
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook
|
|
203
|
+
|
|
204
|
+
app = FastAPI()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@app.post("/webhooks/punchrelay")
|
|
208
|
+
async def punchrelay_webhook(request: Request) -> Response:
|
|
209
|
+
try:
|
|
210
|
+
event = verify_webhook(await request.body(), request.headers, os.environ["PUNCHRELAY_WEBHOOK_SECRET"])
|
|
211
|
+
except WebhookVerificationError:
|
|
212
|
+
return Response(status_code=401)
|
|
213
|
+
|
|
214
|
+
if is_attendance_created(event):
|
|
215
|
+
...
|
|
216
|
+
return Response(status_code=204)
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Django
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
from django.conf import settings
|
|
223
|
+
from django.http import HttpResponse
|
|
224
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
225
|
+
from django.views.decorators.http import require_POST
|
|
226
|
+
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@csrf_exempt
|
|
230
|
+
@require_POST
|
|
231
|
+
def punchrelay_webhook(request):
|
|
232
|
+
try:
|
|
233
|
+
event = verify_webhook(request.body, request.headers, settings.PUNCHRELAY_WEBHOOK_SECRET)
|
|
234
|
+
except WebhookVerificationError:
|
|
235
|
+
return HttpResponse(status=401)
|
|
236
|
+
|
|
237
|
+
if is_attendance_created(event):
|
|
238
|
+
...
|
|
239
|
+
return HttpResponse(status=204)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Use `request.headers`, not `request.META`.
|
|
243
|
+
|
|
244
|
+
### Event types
|
|
245
|
+
|
|
246
|
+
| `event["type"]` | Guard | `event["data"]` |
|
|
247
|
+
|---|---|---|
|
|
248
|
+
| `attendance.created` | `is_attendance_created(event)` | `AttendanceCreated`: the punch, with `id`, `userId`, `userName`, `deviceId`, `deviceSerial`, `punchedAt`, `status`, `punch` |
|
|
249
|
+
| `webhook.test` | `is_webhook_test(event)` | `WebhookTest` |
|
|
250
|
+
|
|
251
|
+
The guards are `TypeGuard`s, so a type checker narrows `event["data"]` after them. New event types may be added. Ignore types you don't recognise and still answer 2xx.
|
|
252
|
+
|
|
253
|
+
`compute_signature(secret, timestamp, body)` produces a valid signature for your own tests.
|
|
254
|
+
|
|
255
|
+
## Options
|
|
256
|
+
|
|
257
|
+
| Option | Default | |
|
|
258
|
+
|---|---|---|
|
|
259
|
+
| `api_key` | (required) | `prk_live_…` |
|
|
260
|
+
| `base_url` | (required) | The API host |
|
|
261
|
+
| `tenant_id` | looked up | Set it to skip the one-time `GET /api/key-info` call |
|
|
262
|
+
| `max_retries` | 3 | 0 turns retries off |
|
|
263
|
+
| `retry_base_delay` | 0.5 | Seconds |
|
|
264
|
+
| `max_retry_delay` | 30 | Seconds |
|
|
265
|
+
| `timeout` | 100 | Seconds per call, including retries. `None` or 0 turns it off |
|
|
266
|
+
| `transport` | httpx's | An `httpx.BaseTransport` (`AsyncBaseTransport` for the async client), for a test stub or custom networking |
|
|
267
|
+
| `proxy` | none | A proxy URL for the default transport |
|
|
268
|
+
|
|
269
|
+
## Contributing
|
|
270
|
+
|
|
271
|
+
`src/punchrelay/_generated/models.py` is produced by [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator) from `sdks/openapi/v1.json`, with the options in `pyproject.toml`. Never edit it by hand. Set up once, then after the spec changes:
|
|
272
|
+
|
|
273
|
+
```sh
|
|
274
|
+
cd sdks/python
|
|
275
|
+
python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt -e . # Windows: .venv\Scripts\pip
|
|
276
|
+
cd .. && ./generate.sh python && cd python # or generate.ps1 python
|
|
277
|
+
.venv/bin/ruff check . && .venv/bin/ruff format --check .
|
|
278
|
+
.venv/bin/mypy # strict; checks the hand-written layer against the new models
|
|
279
|
+
.venv/bin/pytest
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
`tests/test_coverage.py` fails when an operation in the spec has no method in the SDK, or when a method calls a path or HTTP method the spec doesn't have. Webhook signing is tested against `sdks/testdata/webhook-vectors.json`, which the .NET and Node SDKs also use and the API test suite checks against the server's signer.
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
# PunchRelay Python SDK
|
|
2
|
+
|
|
3
|
+
A client for the PunchRelay API. Use it to read attendance from your ZKTeco devices, manage devices, employees, locations and webhooks, and verify webhook signatures.
|
|
4
|
+
|
|
5
|
+
- Python 3.11 or later
|
|
6
|
+
- Package: `punchrelay`, with a sync client (`PunchRelay`) and an asyncio client (`AsyncPunchRelay`), fully typed
|
|
7
|
+
- One dependency: [httpx](https://www.python-httpx.org/)
|
|
8
|
+
- API reference: `https://<api-host>/docs`
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
pip install punchrelay
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
Create a key on the dashboard's **API keys** page. Use a `read` key if you only read data, and a `read_write` key if you also make changes. The key tells the API which organisation you are, so no call takes a tenant id.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import os
|
|
22
|
+
from datetime import datetime, timedelta, timezone
|
|
23
|
+
|
|
24
|
+
from punchrelay import PunchRelay
|
|
25
|
+
|
|
26
|
+
with PunchRelay(api_key=os.environ["PUNCHRELAY_API_KEY"], base_url="https://adms.example.com") as client:
|
|
27
|
+
key = client.get_key_info()
|
|
28
|
+
print(f"{key['tenantName']} ({key['scope']})")
|
|
29
|
+
|
|
30
|
+
# Every punch in the last day, newest first. Pages are fetched as you iterate.
|
|
31
|
+
since = datetime.now(timezone.utc) - timedelta(days=1)
|
|
32
|
+
for punch in client.attendance.list_all(from_=since):
|
|
33
|
+
print(punch["punchedAt"], punch["userId"], punch.get("userName"), "@", punch.get("deviceName"))
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Create one client per key and reuse it. It caches the key's organisation after the first call, keeps a connection pool, and is safe to share between threads. Close it when you are done (`client.close()` or a `with` block).
|
|
37
|
+
|
|
38
|
+
### Async
|
|
39
|
+
|
|
40
|
+
`AsyncPunchRelay` has the same options and methods. Await the calls and iterate the `list_all` helpers with `async for`:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from punchrelay import AsyncPunchRelay
|
|
44
|
+
|
|
45
|
+
async with AsyncPunchRelay(api_key=os.environ["PUNCHRELAY_API_KEY"], base_url="https://adms.example.com") as client:
|
|
46
|
+
devices = await client.devices.list()
|
|
47
|
+
async for punch in client.attendance.list_all(from_=since):
|
|
48
|
+
...
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
It runs on asyncio. Concurrent first calls share one key lookup.
|
|
52
|
+
|
|
53
|
+
## What's covered
|
|
54
|
+
|
|
55
|
+
| Area | Methods |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `client.attendance` | `list`, `list_all`, `get`, `get_stats`, `export_csv`, `delete`, `delete_range` |
|
|
58
|
+
| `client.devices` | `list`, `list_models`, `create`, `update`, `delete`, `activate`, `deactivate`, `reboot`, `pull_attendance`, `pull_users`, `queue_command`, `list_commands`, `set_server_address` |
|
|
59
|
+
| `client.users` | `list`, `list_all`, `create`, `bulk_upsert`, `update`, `delete`, `sync`, `sync_one` |
|
|
60
|
+
| `client.locations` | `list`, `create`, `update`, `delete` |
|
|
61
|
+
| `client.webhooks` | `list`, `list_event_types`, `get`, `create`, `update`, `delete`, `rotate_secret`, `enable`, `disable`, `send_test`, `list_deliveries`, `list_all_deliveries`, `get_delivery`, `redeliver` |
|
|
62
|
+
|
|
63
|
+
### Requests and responses are dicts
|
|
64
|
+
|
|
65
|
+
Responses are plain dicts with the API's camelCase keys, exactly as the API sends them. Request bodies are dicts too. Their types are `TypedDict`s in `punchrelay.models` (`AttendanceItem`, `CreateDeviceRequest`, …), so mypy, Pyright and your editor check the keys:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from punchrelay.models import UpsertUserRequest
|
|
69
|
+
|
|
70
|
+
user: UpsertUserRequest = {"pin": "1005", "name": "Ama Mensah"}
|
|
71
|
+
created = client.users.create(user)
|
|
72
|
+
print(created["id"])
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Every key is typed as optional, because the API may add fields. Index the fields you rely on (`punch["userId"]`), or use `.get()` for the nullable ones.
|
|
76
|
+
|
|
77
|
+
Filters and paging are keyword arguments in snake_case: `from_` (with an underscore, because `from` is a Python keyword), `to`, `user_id`, `device_id`, `location_id`, `page`, `page_size`.
|
|
78
|
+
|
|
79
|
+
### Times and dates
|
|
80
|
+
|
|
81
|
+
- **Timestamps** (`from_` and `to` on attendance) accept a timezone-aware `datetime` or an ISO 8601 string. They are sent as UTC. A naive `datetime` raises `ValueError`, because the SDK cannot know which time zone you meant. Responses return timestamps as ISO 8601 strings.
|
|
82
|
+
- **Calendar dates** (`get_stats`, `pull_attendance`) are days in your organisation's time zone. Pass a `date` or `"YYYY-MM-DD"`.
|
|
83
|
+
|
|
84
|
+
### Anything not wrapped yet
|
|
85
|
+
|
|
86
|
+
`client.http` is the underlying [httpx](https://www.python-httpx.org/) client. It uses the same key, retries and errors as the methods above, with paths relative to `base_url`:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
tenant_id = client.get_tenant_id()
|
|
90
|
+
devices = client.http.get(f"/api/tenants/{tenant_id}/devices").json()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Errors
|
|
94
|
+
|
|
95
|
+
Any non-2xx response raises `PunchRelayError`. It carries:
|
|
96
|
+
|
|
97
|
+
- `status`: the HTTP status
|
|
98
|
+
- `code`: the API's error code, such as `invalid_range` or `forbidden`
|
|
99
|
+
- `message`
|
|
100
|
+
- `body`: the raw response body
|
|
101
|
+
- `retry_after`: seconds, set on a 429
|
|
102
|
+
|
|
103
|
+
When the subscription is suspended (402), the error is a `SubscriptionSuspendedError`. It adds `invoice_number`, `pay_url`, `subscription_status` and `reason`.
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from punchrelay import PunchRelayError, SubscriptionSuspendedError
|
|
107
|
+
|
|
108
|
+
try:
|
|
109
|
+
client.devices.reboot(device_id)
|
|
110
|
+
except SubscriptionSuspendedError as err:
|
|
111
|
+
print(f"Suspended: pay {err.invoice_number} at {err.pay_url}")
|
|
112
|
+
except PunchRelayError as err:
|
|
113
|
+
if err.status == 403:
|
|
114
|
+
print("This key is read-only.")
|
|
115
|
+
else:
|
|
116
|
+
raise
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Network failures raise httpx's `httpx.TransportError` subclasses. A call that runs out of time raises `httpx.TimeoutException`.
|
|
120
|
+
|
|
121
|
+
## Retries
|
|
122
|
+
|
|
123
|
+
These failures are retried up to `max_retries` times (default 3), with jittered exponential backoff:
|
|
124
|
+
|
|
125
|
+
- 429 Too Many Requests, on any method. The SDK waits for the server's `Retry-After`.
|
|
126
|
+
- 500, 502, 503 and 504, only on `GET`, `PUT`, `DELETE`, `HEAD` and `OPTIONS`.
|
|
127
|
+
- Network errors, on the same methods.
|
|
128
|
+
|
|
129
|
+
A `POST` is never retried after a 5xx or a network error, because it may already have run on the server.
|
|
130
|
+
|
|
131
|
+
If `Retry-After` is longer than `max_retry_delay` (default 30 s), the SDK raises the 429 immediately instead of waiting. Each key may make 120 requests per minute.
|
|
132
|
+
|
|
133
|
+
## Verifying webhooks
|
|
134
|
+
|
|
135
|
+
`verify_webhook(raw_body, headers, secret)` checks a webhook and returns its event. It does three things:
|
|
136
|
+
|
|
137
|
+
- checks the HMAC-SHA256 signature, using a constant-time comparison (`hmac.compare_digest`)
|
|
138
|
+
- rejects timestamps more than 5 minutes from your clock (change this with `tolerance=`, in seconds)
|
|
139
|
+
- parses the event
|
|
140
|
+
|
|
141
|
+
It raises `WebhookVerificationError` when any check fails.
|
|
142
|
+
|
|
143
|
+
**Pass the raw body, exactly as it was received.** If you parse the JSON and serialise it again, the bytes change and the signature no longer matches. `raw_body` can be `bytes` or `str`. `headers` can be your framework's request headers or a plain dict; names are matched case-insensitively.
|
|
144
|
+
|
|
145
|
+
### Flask
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
import os
|
|
149
|
+
|
|
150
|
+
from flask import Flask, request
|
|
151
|
+
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook
|
|
152
|
+
|
|
153
|
+
app = Flask(__name__)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@app.post("/webhooks/punchrelay")
|
|
157
|
+
def punchrelay_webhook():
|
|
158
|
+
try:
|
|
159
|
+
event = verify_webhook(request.get_data(), request.headers, os.environ["PUNCHRELAY_WEBHOOK_SECRET"])
|
|
160
|
+
except WebhookVerificationError:
|
|
161
|
+
return "", 401
|
|
162
|
+
|
|
163
|
+
if is_attendance_created(event):
|
|
164
|
+
# Queue it for processing. event["id"] stays the same across retries, so de-duplicate on it.
|
|
165
|
+
print(event["data"]["userId"], event["data"]["punchedAt"])
|
|
166
|
+
return "", 204
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Read `request.get_data()` before touching `request.json` or `request.form`.
|
|
170
|
+
|
|
171
|
+
### FastAPI
|
|
172
|
+
|
|
173
|
+
Take the `Request` and read `await request.body()`. Don't declare a Pydantic model for the body, because FastAPI would parse it first.
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
import os
|
|
177
|
+
|
|
178
|
+
from fastapi import FastAPI, Request, Response
|
|
179
|
+
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook
|
|
180
|
+
|
|
181
|
+
app = FastAPI()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@app.post("/webhooks/punchrelay")
|
|
185
|
+
async def punchrelay_webhook(request: Request) -> Response:
|
|
186
|
+
try:
|
|
187
|
+
event = verify_webhook(await request.body(), request.headers, os.environ["PUNCHRELAY_WEBHOOK_SECRET"])
|
|
188
|
+
except WebhookVerificationError:
|
|
189
|
+
return Response(status_code=401)
|
|
190
|
+
|
|
191
|
+
if is_attendance_created(event):
|
|
192
|
+
...
|
|
193
|
+
return Response(status_code=204)
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Django
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
from django.conf import settings
|
|
200
|
+
from django.http import HttpResponse
|
|
201
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
202
|
+
from django.views.decorators.http import require_POST
|
|
203
|
+
from punchrelay import WebhookVerificationError, is_attendance_created, verify_webhook
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@csrf_exempt
|
|
207
|
+
@require_POST
|
|
208
|
+
def punchrelay_webhook(request):
|
|
209
|
+
try:
|
|
210
|
+
event = verify_webhook(request.body, request.headers, settings.PUNCHRELAY_WEBHOOK_SECRET)
|
|
211
|
+
except WebhookVerificationError:
|
|
212
|
+
return HttpResponse(status=401)
|
|
213
|
+
|
|
214
|
+
if is_attendance_created(event):
|
|
215
|
+
...
|
|
216
|
+
return HttpResponse(status=204)
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Use `request.headers`, not `request.META`.
|
|
220
|
+
|
|
221
|
+
### Event types
|
|
222
|
+
|
|
223
|
+
| `event["type"]` | Guard | `event["data"]` |
|
|
224
|
+
|---|---|---|
|
|
225
|
+
| `attendance.created` | `is_attendance_created(event)` | `AttendanceCreated`: the punch, with `id`, `userId`, `userName`, `deviceId`, `deviceSerial`, `punchedAt`, `status`, `punch` |
|
|
226
|
+
| `webhook.test` | `is_webhook_test(event)` | `WebhookTest` |
|
|
227
|
+
|
|
228
|
+
The guards are `TypeGuard`s, so a type checker narrows `event["data"]` after them. New event types may be added. Ignore types you don't recognise and still answer 2xx.
|
|
229
|
+
|
|
230
|
+
`compute_signature(secret, timestamp, body)` produces a valid signature for your own tests.
|
|
231
|
+
|
|
232
|
+
## Options
|
|
233
|
+
|
|
234
|
+
| Option | Default | |
|
|
235
|
+
|---|---|---|
|
|
236
|
+
| `api_key` | (required) | `prk_live_…` |
|
|
237
|
+
| `base_url` | (required) | The API host |
|
|
238
|
+
| `tenant_id` | looked up | Set it to skip the one-time `GET /api/key-info` call |
|
|
239
|
+
| `max_retries` | 3 | 0 turns retries off |
|
|
240
|
+
| `retry_base_delay` | 0.5 | Seconds |
|
|
241
|
+
| `max_retry_delay` | 30 | Seconds |
|
|
242
|
+
| `timeout` | 100 | Seconds per call, including retries. `None` or 0 turns it off |
|
|
243
|
+
| `transport` | httpx's | An `httpx.BaseTransport` (`AsyncBaseTransport` for the async client), for a test stub or custom networking |
|
|
244
|
+
| `proxy` | none | A proxy URL for the default transport |
|
|
245
|
+
|
|
246
|
+
## Contributing
|
|
247
|
+
|
|
248
|
+
`src/punchrelay/_generated/models.py` is produced by [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator) from `sdks/openapi/v1.json`, with the options in `pyproject.toml`. Never edit it by hand. Set up once, then after the spec changes:
|
|
249
|
+
|
|
250
|
+
```sh
|
|
251
|
+
cd sdks/python
|
|
252
|
+
python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt -e . # Windows: .venv\Scripts\pip
|
|
253
|
+
cd .. && ./generate.sh python && cd python # or generate.ps1 python
|
|
254
|
+
.venv/bin/ruff check . && .venv/bin/ruff format --check .
|
|
255
|
+
.venv/bin/mypy # strict; checks the hand-written layer against the new models
|
|
256
|
+
.venv/bin/pytest
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
`tests/test_coverage.py` fails when an operation in the spec has no method in the SDK, or when a method calls a path or HTTP method the spec doesn't have. Webhook signing is tested against `sdks/testdata/webhook-vectors.json`, which the .NET and Node SDKs also use and the API test suite checks against the server's signer.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "punchrelay"
|
|
7
|
+
# Keep in step with src/punchrelay/_version.py; tests/test_client.py checks it.
|
|
8
|
+
version = "0.1.0"
|
|
9
|
+
description = "Client for the PunchRelay API: attendance from ZKTeco devices, devices, employees, locations, webhooks and webhook signature verification."
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "PunchRelay" }]
|
|
14
|
+
requires-python = ">=3.11"
|
|
15
|
+
dependencies = ["httpx>=0.27,<1"]
|
|
16
|
+
keywords = ["punchrelay", "zkteco", "attendance", "adms", "webhooks"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 4 - Beta",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Programming Language :: Python :: 3.14",
|
|
27
|
+
"Framework :: AsyncIO",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.wheel]
|
|
32
|
+
packages = ["src/punchrelay"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.sdist]
|
|
35
|
+
include = ["src/punchrelay", "README.md", "LICENSE", "pyproject.toml"]
|
|
36
|
+
|
|
37
|
+
# sdks/generate.sh python runs `datamodel-codegen` from this folder, which reads these options.
|
|
38
|
+
[tool.datamodel-codegen]
|
|
39
|
+
input = "../openapi/v1.json"
|
|
40
|
+
input-file-type = "openapi"
|
|
41
|
+
output = "src/punchrelay/_generated/models.py"
|
|
42
|
+
output-model-type = "typing.TypedDict"
|
|
43
|
+
target-python-version = "3.11"
|
|
44
|
+
use-standard-collections = true
|
|
45
|
+
use-union-operator = true
|
|
46
|
+
use-exact-imports = true
|
|
47
|
+
strict-nullable = true
|
|
48
|
+
keep-model-order = true
|
|
49
|
+
disable-timestamp = true
|
|
50
|
+
formatters = ["ruff-format"]
|
|
51
|
+
custom-file-header = "# Generated from sdks/openapi/v1.json by sdks/generate.sh (datamodel-code-generator). Do not edit."
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
line-length = 120
|
|
55
|
+
target-version = "py311"
|
|
56
|
+
extend-exclude = ["src/punchrelay/_generated"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "ASYNC"]
|
|
60
|
+
|
|
61
|
+
[tool.mypy]
|
|
62
|
+
strict = true
|
|
63
|
+
python_version = "3.11"
|
|
64
|
+
files = ["src", "tests"]
|
|
65
|
+
|
|
66
|
+
[tool.pytest.ini_options]
|
|
67
|
+
testpaths = ["tests"]
|
|
68
|
+
asyncio_mode = "auto"
|
|
69
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Client for the PunchRelay API.
|
|
2
|
+
|
|
3
|
+
>>> from punchrelay import PunchRelay
|
|
4
|
+
>>> client = PunchRelay(api_key="prk_live_...", base_url="https://adms.example.com")
|
|
5
|
+
|
|
6
|
+
Request and response types are in :mod:`punchrelay.models`; webhook helpers are also in :mod:`punchrelay.webhooks`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ._client import AsyncPunchRelay, PunchRelay
|
|
10
|
+
from ._convert import DateInput, DateTimeInput
|
|
11
|
+
from ._errors import PunchRelayError, SubscriptionSuspendedError
|
|
12
|
+
from ._version import __version__
|
|
13
|
+
from .resources import WebhookDeliveryStatus
|
|
14
|
+
from .webhooks import (
|
|
15
|
+
DEFAULT_TOLERANCE,
|
|
16
|
+
AttendanceCreated,
|
|
17
|
+
WebhookEvent,
|
|
18
|
+
WebhookEventTypes,
|
|
19
|
+
WebhookTest,
|
|
20
|
+
WebhookVerificationError,
|
|
21
|
+
compute_signature,
|
|
22
|
+
is_attendance_created,
|
|
23
|
+
is_valid_signature,
|
|
24
|
+
is_webhook_test,
|
|
25
|
+
verify_webhook,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"DEFAULT_TOLERANCE",
|
|
30
|
+
"AsyncPunchRelay",
|
|
31
|
+
"AttendanceCreated",
|
|
32
|
+
"DateInput",
|
|
33
|
+
"DateTimeInput",
|
|
34
|
+
"PunchRelay",
|
|
35
|
+
"PunchRelayError",
|
|
36
|
+
"SubscriptionSuspendedError",
|
|
37
|
+
"WebhookDeliveryStatus",
|
|
38
|
+
"WebhookEvent",
|
|
39
|
+
"WebhookEventTypes",
|
|
40
|
+
"WebhookTest",
|
|
41
|
+
"WebhookVerificationError",
|
|
42
|
+
"__version__",
|
|
43
|
+
"compute_signature",
|
|
44
|
+
"is_attendance_created",
|
|
45
|
+
"is_valid_signature",
|
|
46
|
+
"is_webhook_test",
|
|
47
|
+
"verify_webhook",
|
|
48
|
+
]
|