Fullstack Python
Trang chủ / Module 10
📡 Module 10 / 19 · 4 ngày 📅 Tuần 7 ●●●○ Khó

Realtime, file, thanh toán & tìm kiếm trong ứng dụng Python

Các tính năng sản phẩm phổ biến: WebSocket và SSE trong FastAPI (và Django Channels), phát sự kiện qua nhiều instance bằng Redis pub/sub, upload thẳng lên S3 bằng presigned URL, xử lý file nền, thanh toán Stripe và webhook an toàn, tìm kiếm với PostgreSQL full-text/Meilisearch.

WebSocketSSES3/boto3StripeWebhookSearch
📌 Vì sao module này quan trọng

JD Python lương cao thường có "real-time", "payment integration", "file processing" — đặc biệt các sản phẩm có tính năng AI cần stream kết quả và xử lý tài liệu. Khó khăn không nằm ở API thư viện mà ở các vấn đề đi kèm: WebSocket trên nhiều worker process, webhook trùng lặp, file 2GB làm treo worker, đồng bộ index tìm kiếm.

🎯 Mục tiêu học tập

  • Xây WebSocket/SSE trong FastAPI, xác thực kết nối, scale nhiều instance qua Redis pub/sub
  • Upload và tải file qua S3 bằng presigned URL; xử lý file trong background job
  • Tích hợp Stripe Checkout/subscription và webhook có xác minh chữ ký, idempotent
  • Thêm tìm kiếm full-text có lọc tenant
  • Biết Django Channels cho realtime trong hệ Django

WebSocket và SSE

@router.websocket("/ws/projects/{project_id}")
async def project_ws(ws: WebSocket, project_id: int):
    user = await authenticate_ws(ws)                      # cookie/token khi handshake
    if not user or not await can_view(user, project_id):
        await ws.close(code=4403); return
    await ws.accept()
    pubsub = redis.pubsub()
    await pubsub.subscribe(f"project:{project_id}")       # nhận sự kiện từ MỌI instance
    try:
        async for msg in pubsub.listen():
            if msg["type"] == "message":
                await ws.send_text(msg["data"])
    except WebSocketDisconnect:
        pass
    finally:
        await pubsub.unsubscribe(); await pubsub.aclose()

# Khi task thay đổi (API hoặc worker):
await redis.publish(f"project:{task.project_id}", TaskOut.model_validate(task).model_dump_json())

# SSE — đơn giản hơn khi chỉ cần server → client (thông báo, tiến độ job, stream LLM)
@router.get("/jobs/{job_id}/events")
async def job_events(job_id: str):
    async def gen():
        async for progress in watch_job(job_id):
            yield f"data: {json.dumps(progress)}\n\n"
    return StreamingResponse(gen(), media_type="text/event-stream")
  • Mỗi worker Uvicorn là một process riêng — kết nối nằm rải rác, nên phải phát qua pub/sub dùng chung.
  • Database là nguồn sự thật; client reconnect thì tải lại phần thiếu. Django: Channels + channel layer Redis.
  • Dịch vụ managed (Pusher, Ably, Centrifugo) khi không muốn tự vận hành.

File: S3 presigned URL và xử lý nền

s3 = boto3.client("s3")

@router.post("/attachments/upload-url")
async def upload_url(body: UploadRequest, user: UserDep):
    if body.content_type not in {"image/png", "image/jpeg", "application/pdf"} or body.size > 20_000_000:
        raise AppError(422, "INVALID_FILE", "Loại hoặc kích thước file không hợp lệ")
    key = f"uploads/{user.org_id}/{uuid7()}"
    return s3.generate_presigned_post(Bucket=BUCKET, Key=key, ExpiresIn=300,
        Conditions=[["content-length-range", 1, 20_000_000], {"Content-Type": body.content_type}],
        Fields={"Content-Type": body.content_type})

# Sau upload: job kiểm tra magic bytes, quét virus, tạo thumbnail (Pillow), trích văn bản PDF cho tìm kiếm/AI
# Tải file riêng tư: s3.generate_presigned_url("get_object", ..., ExpiresIn=600)

Server Python không giữ file lớn trong RAM; boto3 là đồng bộ — trong endpoint async dùng aioboto3 hoặc asyncio.to_thread. Không tin Content-Type từ client.

Thanh toán và webhook

@router.post("/webhooks/stripe")
async def stripe_webhook(request: Request, session: SessionDep):
    payload = await request.body()                                    # raw body để xác minh chữ ký
    try:
        event = stripe.Webhook.construct_event(payload, request.headers.get("stripe-signature", ""), settings.stripe_webhook_secret.get_secret_value())
    except (ValueError, stripe.SignatureVerificationError):
        raise HTTPException(400)
    inserted = await session.execute(
        insert(WebhookEvent).values(id=event["id"], type=event["type"]).on_conflict_do_nothing().returning(WebhookEvent.id)
    )
    await session.commit()
    if inserted.scalar_one_or_none():                                 # lần đầu nhận sự kiện này
        process_stripe_event.delay(event["id"])                       # xử lý nền, trả 200 nhanh
    return Response(status_code=200)
  • Trạng thái thanh toán chỉ cập nhật từ webhook đã xác minh (hoặc gọi API kiểm tra), không từ trang redirect "success".
  • Webhook trùng/sai thứ tự → idempotent theo event id, quyết định theo trạng thái hiện tại; job đối soát hằng ngày.
  • Cổng nội địa (VNPay, MoMo...): xác minh HMAC theo tài liệu, kiểm tra số tiền và mã đơn khớp.

Tìm kiếm

  • Bắt đầu bằng PostgreSQL: tsvector + GIN index, pg_trgm cho tìm gần đúng, unaccent để bỏ dấu tiếng Việt.
  • Cần xếp hạng tốt, chịu lỗi chính tả, facet nhanh → Meilisearch/Typesense/OpenSearch, đồng bộ qua outbox/job, có lệnh reindex toàn bộ.
  • Tìm kiếm ngữ nghĩa bằng embedding + pgvector — Module 17.
  • Luôn lọc tenant trong truy vấn tìm kiếm.

🏋️ Bài tập thực hành

Kanban realtime có gói trả phí

(1) WebSocket cập nhật board realtime, chạy 2 instance × 2 worker sau Nginx, phát qua Redis pub/sub, kiểm tra quyền khi kết nối. (2) SSE hiển thị tiến độ job xuất CSV. (3) Đính kèm file bằng presigned POST lên MinIO, Celery job tạo thumbnail và kiểm tra magic bytes. (4) Gói Pro bằng Stripe Checkout (test mode), webhook idempotent, test bằng stripe trigger. (5) Tìm kiếm task bằng PostgreSQL full-text + unaccent có lọc tenant, test chứng minh không lộ dữ liệu tổ chức khác.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Realtime chạy đúng trên nhiều process/instance, có kiểm tra quyền
  • File lớn đi thẳng lên object storage, xử lý trong job
  • Webhook xác minh chữ ký, idempotent, xử lý nền
  • Tìm kiếm luôn lọc tenant