| 1 |
import json |
| 2 |
from typing import Any, Dict |
| 3 |
|
| 4 |
from ninja.responses import NinjaJSONEncoder |
| 5 |
|
| 6 |
__all__ = ["StreamFormat", "SSE", "JSONL"] |
| 7 |
|
| 8 |
|
| 9 |
def _serialize_item(item: Any) -> str: |
| 10 |
return json.dumps(item, cls=NinjaJSONEncoder) |
| 11 |
|
| 12 |
|
| 13 |
class _StreamAlias: |
| 14 |
"""Marker created by StreamFormat[ItemType].""" |
| 15 |
|
| 16 |
def __init__(self, format_cls: type, item_type: type) -> None: |
| 17 |
self.format_cls = format_cls |
| 18 |
self.item_type = item_type |
| 19 |
|
| 20 |
|
| 21 |
class StreamFormat: |
| 22 |
"""Base class for streaming formats. Extensible by users.""" |
| 23 |
|
| 24 |
media_type: str |
| 25 |
|
| 26 |
def __class_getitem__(cls, item_type: type) -> "_StreamAlias": |
| 27 |
return _StreamAlias(cls, item_type) |
| 28 |
|
| 29 |
@classmethod |
| 30 |
def format_chunk(cls, data: str) -> str: |
| 31 |
"""Format a serialized JSON string for this stream.""" |
| 32 |
raise NotImplementedError |
| 33 |
|
| 34 |
@classmethod |
| 35 |
def openapi_content_schema(cls, item_schema: dict) -> dict: |
| 36 |
"""Generate OpenAPI content dict for this format.""" |
| 37 |
return {cls.media_type: {"schema": item_schema}} |
| 38 |
|
| 39 |
@classmethod |
| 40 |
def response_headers(cls) -> Dict[str, str]: |
| 41 |
"""Extra headers for the streaming response.""" |
| 42 |
return {} |
| 43 |
|
| 44 |
|
| 45 |
class JSONL(StreamFormat): |
| 46 |
media_type = "application/jsonl" |
| 47 |
|
| 48 |
@classmethod |
| 49 |
def format_chunk(cls, data: str) -> str: |
| 50 |
return data + "\n" |
| 51 |
|
| 52 |
|
| 53 |
class SSE(StreamFormat): |
| 54 |
media_type = "text/event-stream" |
| 55 |
|
| 56 |
@classmethod |
| 57 |
def format_chunk(cls, data: str) -> str: |
| 58 |
return f"data: {data}\n\n" |
| 59 |
|
| 60 |
@classmethod |
| 61 |
def response_headers(cls) -> Dict[str, str]: |
| 62 |
return {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"} |
| 63 |
|
| 64 |
@classmethod |
| 65 |
def openapi_content_schema(cls, item_schema: dict) -> dict: |
| 66 |
return { |
| 67 |
cls.media_type: { |
| 68 |
"schema": { |
| 69 |
"type": "object", |
| 70 |
"properties": { |
| 71 |
"data": item_schema, |
| 72 |
}, |
| 73 |
"description": "SSE event with JSON data payload", |
| 74 |
} |
| 75 |
} |
| 76 |
} |