Python SDK
التثبيت
Section titled “التثبيت”pip install tkawen# أوuv pip install tkawen# أوpoetry add tkawenيتطلّب:
- Python 3.10+ (يستخدم match statements + structural pattern matching)
httpx(async HTTP)pydantic2.x (validation)
التهيئة
Section titled “التهيئة”from tkawen import Tkawenimport os
tk = Tkawen( key=os.environ['TKAWEN_KEY'], base_url='https://api.tkawen.com', # افتراضي timeout=30.0, # seconds max_retries=3,)الاستدعاء الأوّل
Section titled “الاستدعاء الأوّل”Sync (افتراضيّ)
Section titled “Sync (افتراضيّ)”room = tk.connect.rooms.create( name='demo', max_participants=4,)
print(room.join_url)# → https://meet.liqaa.io/rm_8x2k9dAsync (المُفضَّل للـ web frameworks)
Section titled “Async (المُفضَّل للـ web frameworks)”import asynciofrom tkawen import AsyncTkawen
async def main(): async with AsyncTkawen(key=os.environ['TKAWEN_KEY']) as tk: room = await tk.connect.rooms.create( name='demo', max_participants=4, ) return room.join_url
print(asyncio.run(main()))التغطية
Section titled “التغطية”كلّ الطبقات السبع:
tk.identity.verify(...) # 01tk.connect.rooms.create(...) # 02tk.pay.checkouts.create(...) # 03tk.commerce.stores.create(...) # 04tk.knowledge.certificates.issue(...) # 05tk.logistics.shipments.create(...) # 06tk.usage.current() # 07كلّ الاستدعاءات typed بـ Pydantic models — IntelliSense كامل، validation تلقائيّ.
معالجة الأخطاء
Section titled “معالجة الأخطاء”from tkawen import ( TkawenError, QuotaExceededError, InvalidParamError, AuthError,)
try: tk.connect.rooms.create(name='')except InvalidParamError as e: print(f"الحقل {e.field} غير صحيح: {e.expected}")except QuotaExceededError as e: print(f"تجاوزت الحدّ ({e.used}/{e.limit})")except TkawenError as e: print(f"خطأ: {e.code} — {e}")Webhooks (FastAPI example)
Section titled “Webhooks (FastAPI example)”from fastapi import FastAPI, Request, HTTPExceptionfrom tkawen import verify_webhook
app = FastAPI()WEBHOOK_SECRET = os.environ['TKAWEN_WEBHOOK_SECRET']
@app.post('/tkawen-webhook')async def webhook(request: Request): payload = await request.body() signature = request.headers.get('x-tkawen-signature', '')
if not verify_webhook(payload, signature, WEBHOOK_SECRET): raise HTTPException(401, 'invalid signature')
event = await request.json()
match event['type']: case 'room.ended': await process_recording(event['data']) case 'checkout.completed': await process_order(event['data']) case 'shipment.delivered': await notify_customer(event['data'])
return {'received': True}Django example
Section titled “Django example”from django.views.decorators.csrf import csrf_exemptfrom django.http import HttpResponse, HttpResponseForbiddenfrom tkawen import verify_webhook
@csrf_exemptdef tkawen_webhook(request): payload = request.body signature = request.headers.get('X-TKAWEN-Signature', '')
if not verify_webhook(payload, signature, settings.TKAWEN_WEBHOOK_SECRET): return HttpResponseForbidden()
event = json.loads(payload) # ... معالجة الـ event return HttpResponse(status=200)Streaming (للـ AI Tutor + TTS)
Section titled “Streaming (للـ AI Tutor + TTS)”async for chunk in tk.knowledge.ai_tutor.stream( course_id='crs_abc', question='اشرح TVA بالعربية',): print(chunk.text, end='', flush=True)Bulk operations
Section titled “Bulk operations”# استيراد 5,000 منتجproducts = [ {'name': f'منتج {i}', 'price': 1000 + i, 'currency': 'DZD'} for i in range(5000)]
result = tk.commerce.products.bulk( store_id='st_8xk2', products=products, batch_size=500, # افتراضيّ on_progress=lambda n, total: print(f'{n}/{total}'),)print(f"نجح: {result.success_count}, فشل: {result.error_count}")Pandas integration
Section titled “Pandas integration”import pandas as pd
# اقرأ كلّ الـ transactions كـ DataFramedf = tk.pay.transactions.to_dataframe( period='2026-05', columns=['id', 'amount', 'currency', 'status', 'created_at'],)
df.groupby('status')['amount'].sum()CLI (مدمج)
Section titled “CLI (مدمج)”# الـ pip install يضيف tkawen CLItkawen --helptkawen usagetkawen connect.rooms.create --name=demo --max=4tkawen --json keys.list # للـ scriptingأمثلة كاملة
Section titled “أمثلة كاملة”مستودع tkawen-python-examples:
examples/fastapi-checkoutexamples/django-identity-ssoexamples/celery-bulk-importexamples/data-pipeline— استخراج Pandas + plot Matplotlib
git clone https://github.com/hartemyaakoub/tkawen-python-examplescd tkawen-python-examples/examples/fastapi-checkoutpip install -r requirements.txtuvicorn main:app --reloadالنسخة + التغيير
Section titled “النسخة + التغيير”- آخر إصدار: 1.0.x
- Python minimum: 3.10
- Changelog: github.com/hartemyaakoub/tkawen-python/releases
المساهمة
Section titled “المساهمة”github.com/hartemyaakoub/tkawen-python — MIT.
- Discord: discord.gg/tkawen #python-sdk
- البريد: DIRECTION@takawen.dz