vexor-video-sdk 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vexor
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,350 @@
1
+ Metadata-Version: 2.4
2
+ Name: vexor-video-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for Vexor Video Platform
5
+ Author-email: Vexor Team <dev@vexor.et>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://vexor.et
8
+ Project-URL: Documentation, https://vexor.et/docs#integrations
9
+ Keywords: video,hls,transcoding,streaming,vexor
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Multimedia :: Video
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # Vexor Python SDK
19
+
20
+ The official Python client for the [Vexor](https://vexor.et) video platform.
21
+
22
+ - **Zero dependencies**: Pure Python standard library (`urllib`, `hmac`, `hashlib`, `json`). No `requests`, `urllib3`, or `aiohttp` dependency conflicts.
23
+ - **Resumable uploads**: Built-in chunked [tus](https://tus.io) client with progress callbacks and automatic retry.
24
+ - **Playback security**: Requests short-lived Ed25519 playback tokens for AES-128 encrypted HLS streaming.
25
+ - **Cryptographic webhooks**: Automatic HMAC-SHA256 signature verification.
26
+ - **Type-hinted**: Type hints on the public API; Python 3.9+.
27
+
28
+ ---
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install vexor-video-sdk
34
+ ```
35
+
36
+ For local development in a repository checkout, install the package in editable mode from this directory:
37
+ ```bash
38
+ pip install -e .
39
+ ```
40
+
41
+ The SDK reads `VEXOR_API_KEY` and `VEXOR_BASE_URL` from the environment. The
42
+ base URL must use HTTPS except for `localhost`, `127.0.0.1`, or `::1` during
43
+ local development.
44
+
45
+ ---
46
+
47
+ ## Quickstart
48
+
49
+ ```python
50
+ from vexor_video import Vexor
51
+
52
+ # Initialize client (defaults to VEXOR_API_KEY and VEXOR_BASE_URL env vars)
53
+ client = Vexor(api_key="vex_live_your_key_here")
54
+
55
+ # 1. Upload a video (resumable tus upload with progress tracking)
56
+ def on_progress(uploaded, total):
57
+ percent = (uploaded / total) * 100
58
+ print(f"Uploading: {percent:.1f}% ({uploaded}/{total} bytes)")
59
+
60
+ asset = client.assets.upload(
61
+ "lecture.mp4",
62
+ title="Introduction to Calculus",
63
+ on_progress=on_progress,
64
+ )
65
+ print(f"Asset created: {asset['id']}")
66
+
67
+ # 2. Generate a secure playback session (when asset state is 'ready')
68
+ playback = client.tokens.create(
69
+ asset_id=asset["id"],
70
+ viewer_id="user_12345",
71
+ )
72
+ print(f"Playable HLS Manifest: {playback['manifest_url']}")
73
+ print(f"Thumbnail: {playback.get('thumbnail_url')}")
74
+ ```
75
+
76
+ ## Importing from your storage
77
+
78
+ When your source videos already live in an S3-compatible bucket, connect it once and import objects by key instead of re-uploading their bytes through your application. The connection endpoint must be public HTTPS. VEXOR encrypts the submitted credentials at rest and only returns a masked key hint.
79
+
80
+ ```python
81
+ import os
82
+
83
+ connection = client.storage_connections.create(
84
+ name="Course videos",
85
+ endpoint="https://s3.example.net",
86
+ region="us-east-1",
87
+ bucket="course-media",
88
+ prefix="published",
89
+ access_key_id=os.environ["COURSE_STORAGE_ACCESS_KEY"],
90
+ secret_access_key=os.environ["COURSE_STORAGE_SECRET_KEY"],
91
+ )
92
+
93
+ asset = client.assets.import_from_storage(
94
+ connection_id=connection["id"],
95
+ object_key="lesson-01.mp4", # relative to the configured prefix
96
+ )
97
+ print(asset["id"], asset["state"])
98
+ ```
99
+
100
+ For AWS S3, the SDK also supports VEXOR's role-delegation flow. Use an IAM
101
+ role scoped to the intended bucket. First retrieve VEXOR's deployment
102
+ principal with `client.storage_connections.aws_identity()` and use it in the
103
+ role trust policy. Create and retain a unique external ID of at least 16
104
+ characters for the connection; do not include static keys in this mode:
105
+
106
+ ```python
107
+ connection = client.storage_connections.create(
108
+ name="Course videos",
109
+ bucket="course-media",
110
+ region="us-east-1",
111
+ auth_mode="aws_role",
112
+ role_arn="arn:aws:iam::123456789012:role/VexorSourceReader",
113
+ external_id=os.environ["VEXOR_AWS_EXTERNAL_ID"],
114
+ )
115
+ ```
116
+
117
+ The identity endpoint requires VEXOR to be running with its AWS deployment
118
+ identity and STS `GetCallerIdentity` access. A local VEXOR deployment without
119
+ AWS credentials cannot create or verify AWS role connections.
120
+
121
+ The imported original stays in your bucket. VEXOR reads it asynchronously, stores processed HLS in its managed media origin, and handles signed playback delivery. Customer-managed output is a later option that deployments can explicitly enable. Processing status and webhooks use the normal asset lifecycle. See the [public storage and upload docs](https://vexor.et/docs#uploads) for supported flows and permissions.
122
+
123
+ ---
124
+
125
+ ## Asset Management
126
+
127
+ ### Uploading Videos
128
+ The `upload` method supports local file paths, open binary file objects, and in-memory bytes:
129
+
130
+ ```python
131
+ # From a file path:
132
+ asset = client.assets.upload("/path/to/video.mov")
133
+
134
+ # From an open file handle (e.g. Django UploadedFile, FastAPI UploadFile):
135
+ asset = client.assets.upload(file_obj, filename="upload.mp4")
136
+
137
+ # From bytes:
138
+ asset = client.assets.upload(raw_bytes, filename="stream.mp4")
139
+ ```
140
+
141
+ ### Retrieving & Listing Assets
142
+ ```python
143
+ # Get single asset metadata and transcoding status
144
+ asset = client.assets.get("ea56fdde-ad35-44f6-ad9a-8cd01c4f10d1")
145
+ print(asset["state"]) # 'uploading', 'uploaded', 'transcoding', 'ready', or 'failed'
146
+
147
+ # List assets with cursor pagination
148
+ page = client.assets.list_page(limit=25)
149
+ for asset in page["data"]:
150
+ print(asset["id"], asset["filename"], asset["state"])
151
+
152
+ if page["next_cursor"]:
153
+ next_page = client.assets.list_page(limit=25, cursor=page["next_cursor"])
154
+ ```
155
+
156
+ Uploads retry transient failures. `UploadError.upload_url` contains the Tus
157
+ session URL when an upload fails. To resume after a process restart, save the
158
+ URL as soon as it is created with `on_upload_created`, then pass it back with
159
+ the same complete file. Store the URL securely. Resuming checks the session
160
+ size and requires a seekable file when starting from a non-zero offset.
161
+
162
+ ### Deleting Assets
163
+ ```python
164
+ # Queues asset deletion; VEXOR removes its managed media and associated records.
165
+ client.assets.delete("ea56fdde-ad35-44f6-ad9a-8cd01c4f10d1")
166
+ ```
167
+
168
+ ---
169
+
170
+ ## Playback & Tokens
171
+
172
+ Vexor media is encrypted with AES-128 CBC. Video segments can only be decrypted with short-lived tokens:
173
+
174
+ ```python
175
+ session = client.tokens.create(
176
+ asset_id="ea56fdde-ad35-44f6-ad9a-8cd01c4f10d1",
177
+ viewer_id="student_987", # Used for dynamic session watermarking
178
+ session_id="device_sess_xyz", # Optional: limits concurrent playback
179
+ )
180
+
181
+ manifest_url = session["manifest_url"]
182
+ # Pass manifest_url directly to Video.js, HLS.js, ExoPlayer, or AVPlayer
183
+ ```
184
+
185
+ If the asset is still transcoding, `client.tokens.create()` raises `ConflictError` (HTTP 409).
186
+
187
+ ---
188
+
189
+ ## Webhook Verification
190
+
191
+ Vexor signs all webhook requests using HMAC-SHA256 via the `X-Vexor-Signature` header.
192
+
193
+ ### Standalone Webhook Helper
194
+ ```python
195
+ from vexor_video import Webhooks, SignatureVerificationError
196
+
197
+ raw_body = request.body # bytes
198
+ signature = request.headers.get("X-Vexor-Signature")
199
+
200
+ try:
201
+ event = Webhooks.construct(raw_body, signature, secret="whsec_...")
202
+ if event["type"] == "video.asset.ready":
203
+ asset_id = event["asset_id"]
204
+ print(f"Asset {asset_id} is ready for playback!")
205
+ except SignatureVerificationError:
206
+ return "Invalid signature", 400
207
+ ```
208
+
209
+ ---
210
+
211
+ ## Framework Integration Examples
212
+
213
+ ### Django
214
+
215
+ ```python
216
+ # views.py
217
+ import json
218
+ from django.http import JsonResponse, HttpResponse
219
+ from django.views.decorators.csrf import csrf_exempt
220
+ from vexor_video import Vexor, Webhooks, SignatureVerificationError, ConflictError
221
+
222
+ client = Vexor() # reads VEXOR_API_KEY and VEXOR_WEBHOOK_SECRET from env
223
+
224
+ @csrf_exempt
225
+ def vexor_webhook_view(request):
226
+ if request.method != "POST":
227
+ return HttpResponse(status=405)
228
+
229
+ signature = request.headers.get("X-Vexor-Signature", "")
230
+ try:
231
+ event = Webhooks.construct(request.body, signature, client.webhook_secret)
232
+ except SignatureVerificationError:
233
+ return HttpResponse("Invalid signature", status=400)
234
+
235
+ event_type = event.get("type")
236
+ if event_type == "video.asset.ready":
237
+ asset_id = event["asset_id"]
238
+ # Update database: Lesson.objects.filter(vexor_asset_id=asset_id).update(status="ready")
239
+
240
+ return HttpResponse(status=200)
241
+
242
+ def get_lesson_stream(request, lesson_id):
243
+ lesson = Lesson.objects.get(id=lesson_id)
244
+ try:
245
+ playback = client.tokens.create(
246
+ asset_id=lesson.vexor_asset_id,
247
+ viewer_id=str(request.user.id),
248
+ )
249
+ return JsonResponse({"manifest_url": playback["manifest_url"]})
250
+ except ConflictError:
251
+ return JsonResponse({"error": "Video is still processing"}, status=409)
252
+ ```
253
+
254
+ ### FastAPI
255
+
256
+ ```python
257
+ from fastapi import FastAPI, Header, HTTPException, Request
258
+ from vexor_video import Vexor, Webhooks, SignatureVerificationError, ConflictError
259
+
260
+ app = FastAPI()
261
+ vexor = Vexor()
262
+
263
+ @app.post("/webhooks/vexor")
264
+ async def handle_vexor_webhook(
265
+ request: Request,
266
+ x_vexor_signature: str = Header(None),
267
+ ):
268
+ body = await request.body()
269
+ try:
270
+ event = Webhooks.construct(body, x_vexor_signature, vexor.webhook_secret)
271
+ except SignatureVerificationError:
272
+ raise HTTPException(status_code=400, detail="Invalid signature")
273
+
274
+ if event["type"] == "video.asset.ready":
275
+ print(f"Ready: {event['asset_id']}")
276
+
277
+ return {"status": "ok"}
278
+ ```
279
+
280
+ ### Flask
281
+
282
+ ```python
283
+ from flask import Flask, request, jsonify
284
+ from vexor_video import Vexor, Webhooks, SignatureVerificationError
285
+
286
+ app = Flask(__name__)
287
+ vexor = Vexor()
288
+
289
+ @app.route("/webhooks/vexor", methods=["POST"])
290
+ def webhook():
291
+ signature = request.headers.get("X-Vexor-Signature", "")
292
+ try:
293
+ event = Webhooks.construct(request.get_data(), signature, vexor.webhook_secret)
294
+ except SignatureVerificationError:
295
+ return "Invalid signature", 400
296
+
297
+ return jsonify({"received": True})
298
+ ```
299
+
300
+ ---
301
+
302
+ ## Error Handling
303
+
304
+ All SDK errors inherit from `vexor_video.VexorError`:
305
+
306
+ ```python
307
+ from vexor_video import (
308
+ Vexor,
309
+ VexorError,
310
+ AuthenticationError,
311
+ PermissionError,
312
+ NotFoundError,
313
+ ConflictError,
314
+ RateLimitError,
315
+ UploadError,
316
+ )
317
+
318
+ try:
319
+ playback = client.tokens.create(asset_id="some-id")
320
+ except ConflictError as e:
321
+ # Asset is still encoding / not yet ready
322
+ print(f"Video is still processing: {e}")
323
+ except NotFoundError:
324
+ # Asset does not exist
325
+ print("Video not found")
326
+ except AuthenticationError:
327
+ # Invalid or missing API key
328
+ print("Check your Vexor API key")
329
+ except PermissionError:
330
+ # The key is valid but lacks access to this account or resource
331
+ print("Check the API key permissions")
332
+ except RateLimitError:
333
+ # Rate limit hit
334
+ print("Back off and retry")
335
+ # error.retry_after_seconds is populated when the API provides Retry-After.
336
+ except VexorError as e:
337
+ print(f"API Error ({e.status_code}): {e.message}")
338
+ ```
339
+
340
+ ---
341
+
342
+ ## Support Vexor
343
+
344
+ If Vexor helps your product, you can support its continued development on [Support Vexor](https://buymeacoffee.com/eyob_dev).
345
+
346
+ ## License
347
+
348
+ The Python SDK is licensed under the MIT License. This license applies to this package and is separate from the proprietary license for the rest of the Vexor repository. See [LICENSE](LICENSE).
349
+
350
+ MIT © [Vexor](https://vexor.et)
@@ -0,0 +1,333 @@
1
+ # Vexor Python SDK
2
+
3
+ The official Python client for the [Vexor](https://vexor.et) video platform.
4
+
5
+ - **Zero dependencies**: Pure Python standard library (`urllib`, `hmac`, `hashlib`, `json`). No `requests`, `urllib3`, or `aiohttp` dependency conflicts.
6
+ - **Resumable uploads**: Built-in chunked [tus](https://tus.io) client with progress callbacks and automatic retry.
7
+ - **Playback security**: Requests short-lived Ed25519 playback tokens for AES-128 encrypted HLS streaming.
8
+ - **Cryptographic webhooks**: Automatic HMAC-SHA256 signature verification.
9
+ - **Type-hinted**: Type hints on the public API; Python 3.9+.
10
+
11
+ ---
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install vexor-video-sdk
17
+ ```
18
+
19
+ For local development in a repository checkout, install the package in editable mode from this directory:
20
+ ```bash
21
+ pip install -e .
22
+ ```
23
+
24
+ The SDK reads `VEXOR_API_KEY` and `VEXOR_BASE_URL` from the environment. The
25
+ base URL must use HTTPS except for `localhost`, `127.0.0.1`, or `::1` during
26
+ local development.
27
+
28
+ ---
29
+
30
+ ## Quickstart
31
+
32
+ ```python
33
+ from vexor_video import Vexor
34
+
35
+ # Initialize client (defaults to VEXOR_API_KEY and VEXOR_BASE_URL env vars)
36
+ client = Vexor(api_key="vex_live_your_key_here")
37
+
38
+ # 1. Upload a video (resumable tus upload with progress tracking)
39
+ def on_progress(uploaded, total):
40
+ percent = (uploaded / total) * 100
41
+ print(f"Uploading: {percent:.1f}% ({uploaded}/{total} bytes)")
42
+
43
+ asset = client.assets.upload(
44
+ "lecture.mp4",
45
+ title="Introduction to Calculus",
46
+ on_progress=on_progress,
47
+ )
48
+ print(f"Asset created: {asset['id']}")
49
+
50
+ # 2. Generate a secure playback session (when asset state is 'ready')
51
+ playback = client.tokens.create(
52
+ asset_id=asset["id"],
53
+ viewer_id="user_12345",
54
+ )
55
+ print(f"Playable HLS Manifest: {playback['manifest_url']}")
56
+ print(f"Thumbnail: {playback.get('thumbnail_url')}")
57
+ ```
58
+
59
+ ## Importing from your storage
60
+
61
+ When your source videos already live in an S3-compatible bucket, connect it once and import objects by key instead of re-uploading their bytes through your application. The connection endpoint must be public HTTPS. VEXOR encrypts the submitted credentials at rest and only returns a masked key hint.
62
+
63
+ ```python
64
+ import os
65
+
66
+ connection = client.storage_connections.create(
67
+ name="Course videos",
68
+ endpoint="https://s3.example.net",
69
+ region="us-east-1",
70
+ bucket="course-media",
71
+ prefix="published",
72
+ access_key_id=os.environ["COURSE_STORAGE_ACCESS_KEY"],
73
+ secret_access_key=os.environ["COURSE_STORAGE_SECRET_KEY"],
74
+ )
75
+
76
+ asset = client.assets.import_from_storage(
77
+ connection_id=connection["id"],
78
+ object_key="lesson-01.mp4", # relative to the configured prefix
79
+ )
80
+ print(asset["id"], asset["state"])
81
+ ```
82
+
83
+ For AWS S3, the SDK also supports VEXOR's role-delegation flow. Use an IAM
84
+ role scoped to the intended bucket. First retrieve VEXOR's deployment
85
+ principal with `client.storage_connections.aws_identity()` and use it in the
86
+ role trust policy. Create and retain a unique external ID of at least 16
87
+ characters for the connection; do not include static keys in this mode:
88
+
89
+ ```python
90
+ connection = client.storage_connections.create(
91
+ name="Course videos",
92
+ bucket="course-media",
93
+ region="us-east-1",
94
+ auth_mode="aws_role",
95
+ role_arn="arn:aws:iam::123456789012:role/VexorSourceReader",
96
+ external_id=os.environ["VEXOR_AWS_EXTERNAL_ID"],
97
+ )
98
+ ```
99
+
100
+ The identity endpoint requires VEXOR to be running with its AWS deployment
101
+ identity and STS `GetCallerIdentity` access. A local VEXOR deployment without
102
+ AWS credentials cannot create or verify AWS role connections.
103
+
104
+ The imported original stays in your bucket. VEXOR reads it asynchronously, stores processed HLS in its managed media origin, and handles signed playback delivery. Customer-managed output is a later option that deployments can explicitly enable. Processing status and webhooks use the normal asset lifecycle. See the [public storage and upload docs](https://vexor.et/docs#uploads) for supported flows and permissions.
105
+
106
+ ---
107
+
108
+ ## Asset Management
109
+
110
+ ### Uploading Videos
111
+ The `upload` method supports local file paths, open binary file objects, and in-memory bytes:
112
+
113
+ ```python
114
+ # From a file path:
115
+ asset = client.assets.upload("/path/to/video.mov")
116
+
117
+ # From an open file handle (e.g. Django UploadedFile, FastAPI UploadFile):
118
+ asset = client.assets.upload(file_obj, filename="upload.mp4")
119
+
120
+ # From bytes:
121
+ asset = client.assets.upload(raw_bytes, filename="stream.mp4")
122
+ ```
123
+
124
+ ### Retrieving & Listing Assets
125
+ ```python
126
+ # Get single asset metadata and transcoding status
127
+ asset = client.assets.get("ea56fdde-ad35-44f6-ad9a-8cd01c4f10d1")
128
+ print(asset["state"]) # 'uploading', 'uploaded', 'transcoding', 'ready', or 'failed'
129
+
130
+ # List assets with cursor pagination
131
+ page = client.assets.list_page(limit=25)
132
+ for asset in page["data"]:
133
+ print(asset["id"], asset["filename"], asset["state"])
134
+
135
+ if page["next_cursor"]:
136
+ next_page = client.assets.list_page(limit=25, cursor=page["next_cursor"])
137
+ ```
138
+
139
+ Uploads retry transient failures. `UploadError.upload_url` contains the Tus
140
+ session URL when an upload fails. To resume after a process restart, save the
141
+ URL as soon as it is created with `on_upload_created`, then pass it back with
142
+ the same complete file. Store the URL securely. Resuming checks the session
143
+ size and requires a seekable file when starting from a non-zero offset.
144
+
145
+ ### Deleting Assets
146
+ ```python
147
+ # Queues asset deletion; VEXOR removes its managed media and associated records.
148
+ client.assets.delete("ea56fdde-ad35-44f6-ad9a-8cd01c4f10d1")
149
+ ```
150
+
151
+ ---
152
+
153
+ ## Playback & Tokens
154
+
155
+ Vexor media is encrypted with AES-128 CBC. Video segments can only be decrypted with short-lived tokens:
156
+
157
+ ```python
158
+ session = client.tokens.create(
159
+ asset_id="ea56fdde-ad35-44f6-ad9a-8cd01c4f10d1",
160
+ viewer_id="student_987", # Used for dynamic session watermarking
161
+ session_id="device_sess_xyz", # Optional: limits concurrent playback
162
+ )
163
+
164
+ manifest_url = session["manifest_url"]
165
+ # Pass manifest_url directly to Video.js, HLS.js, ExoPlayer, or AVPlayer
166
+ ```
167
+
168
+ If the asset is still transcoding, `client.tokens.create()` raises `ConflictError` (HTTP 409).
169
+
170
+ ---
171
+
172
+ ## Webhook Verification
173
+
174
+ Vexor signs all webhook requests using HMAC-SHA256 via the `X-Vexor-Signature` header.
175
+
176
+ ### Standalone Webhook Helper
177
+ ```python
178
+ from vexor_video import Webhooks, SignatureVerificationError
179
+
180
+ raw_body = request.body # bytes
181
+ signature = request.headers.get("X-Vexor-Signature")
182
+
183
+ try:
184
+ event = Webhooks.construct(raw_body, signature, secret="whsec_...")
185
+ if event["type"] == "video.asset.ready":
186
+ asset_id = event["asset_id"]
187
+ print(f"Asset {asset_id} is ready for playback!")
188
+ except SignatureVerificationError:
189
+ return "Invalid signature", 400
190
+ ```
191
+
192
+ ---
193
+
194
+ ## Framework Integration Examples
195
+
196
+ ### Django
197
+
198
+ ```python
199
+ # views.py
200
+ import json
201
+ from django.http import JsonResponse, HttpResponse
202
+ from django.views.decorators.csrf import csrf_exempt
203
+ from vexor_video import Vexor, Webhooks, SignatureVerificationError, ConflictError
204
+
205
+ client = Vexor() # reads VEXOR_API_KEY and VEXOR_WEBHOOK_SECRET from env
206
+
207
+ @csrf_exempt
208
+ def vexor_webhook_view(request):
209
+ if request.method != "POST":
210
+ return HttpResponse(status=405)
211
+
212
+ signature = request.headers.get("X-Vexor-Signature", "")
213
+ try:
214
+ event = Webhooks.construct(request.body, signature, client.webhook_secret)
215
+ except SignatureVerificationError:
216
+ return HttpResponse("Invalid signature", status=400)
217
+
218
+ event_type = event.get("type")
219
+ if event_type == "video.asset.ready":
220
+ asset_id = event["asset_id"]
221
+ # Update database: Lesson.objects.filter(vexor_asset_id=asset_id).update(status="ready")
222
+
223
+ return HttpResponse(status=200)
224
+
225
+ def get_lesson_stream(request, lesson_id):
226
+ lesson = Lesson.objects.get(id=lesson_id)
227
+ try:
228
+ playback = client.tokens.create(
229
+ asset_id=lesson.vexor_asset_id,
230
+ viewer_id=str(request.user.id),
231
+ )
232
+ return JsonResponse({"manifest_url": playback["manifest_url"]})
233
+ except ConflictError:
234
+ return JsonResponse({"error": "Video is still processing"}, status=409)
235
+ ```
236
+
237
+ ### FastAPI
238
+
239
+ ```python
240
+ from fastapi import FastAPI, Header, HTTPException, Request
241
+ from vexor_video import Vexor, Webhooks, SignatureVerificationError, ConflictError
242
+
243
+ app = FastAPI()
244
+ vexor = Vexor()
245
+
246
+ @app.post("/webhooks/vexor")
247
+ async def handle_vexor_webhook(
248
+ request: Request,
249
+ x_vexor_signature: str = Header(None),
250
+ ):
251
+ body = await request.body()
252
+ try:
253
+ event = Webhooks.construct(body, x_vexor_signature, vexor.webhook_secret)
254
+ except SignatureVerificationError:
255
+ raise HTTPException(status_code=400, detail="Invalid signature")
256
+
257
+ if event["type"] == "video.asset.ready":
258
+ print(f"Ready: {event['asset_id']}")
259
+
260
+ return {"status": "ok"}
261
+ ```
262
+
263
+ ### Flask
264
+
265
+ ```python
266
+ from flask import Flask, request, jsonify
267
+ from vexor_video import Vexor, Webhooks, SignatureVerificationError
268
+
269
+ app = Flask(__name__)
270
+ vexor = Vexor()
271
+
272
+ @app.route("/webhooks/vexor", methods=["POST"])
273
+ def webhook():
274
+ signature = request.headers.get("X-Vexor-Signature", "")
275
+ try:
276
+ event = Webhooks.construct(request.get_data(), signature, vexor.webhook_secret)
277
+ except SignatureVerificationError:
278
+ return "Invalid signature", 400
279
+
280
+ return jsonify({"received": True})
281
+ ```
282
+
283
+ ---
284
+
285
+ ## Error Handling
286
+
287
+ All SDK errors inherit from `vexor_video.VexorError`:
288
+
289
+ ```python
290
+ from vexor_video import (
291
+ Vexor,
292
+ VexorError,
293
+ AuthenticationError,
294
+ PermissionError,
295
+ NotFoundError,
296
+ ConflictError,
297
+ RateLimitError,
298
+ UploadError,
299
+ )
300
+
301
+ try:
302
+ playback = client.tokens.create(asset_id="some-id")
303
+ except ConflictError as e:
304
+ # Asset is still encoding / not yet ready
305
+ print(f"Video is still processing: {e}")
306
+ except NotFoundError:
307
+ # Asset does not exist
308
+ print("Video not found")
309
+ except AuthenticationError:
310
+ # Invalid or missing API key
311
+ print("Check your Vexor API key")
312
+ except PermissionError:
313
+ # The key is valid but lacks access to this account or resource
314
+ print("Check the API key permissions")
315
+ except RateLimitError:
316
+ # Rate limit hit
317
+ print("Back off and retry")
318
+ # error.retry_after_seconds is populated when the API provides Retry-After.
319
+ except VexorError as e:
320
+ print(f"API Error ({e.status_code}): {e.message}")
321
+ ```
322
+
323
+ ---
324
+
325
+ ## Support Vexor
326
+
327
+ If Vexor helps your product, you can support its continued development on [Support Vexor](https://buymeacoffee.com/eyob_dev).
328
+
329
+ ## License
330
+
331
+ The Python SDK is licensed under the MIT License. This license applies to this package and is separate from the proprietary license for the rest of the Vexor repository. See [LICENSE](LICENSE).
332
+
333
+ MIT © [Vexor](https://vexor.et)