fastlib-py 0.2.9__tar.gz → 0.3.2__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.
Files changed (76) hide show
  1. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/LICENSE +21 -21
  2. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/PKG-INFO +1 -1
  3. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/__init__.py +0 -2
  4. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/_server_config.py +2 -0
  5. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/loader.py +1 -1
  6. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/manager.py +4 -4
  7. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/i18n/messages.py +1 -1
  8. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/middleware/i18n.py +40 -40
  9. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/middleware/jwt.py +2 -1
  10. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/stream/enums.py +36 -36
  11. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/stream/event.py +101 -101
  12. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/stream/handler.py +187 -187
  13. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/stream/schema.py +140 -140
  14. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/stream/sse.py +272 -272
  15. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib_py.egg-info/PKG-INFO +1 -1
  16. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/pyproject.toml +127 -127
  17. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/README.md +0 -0
  18. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/cache/__init__.py +0 -0
  19. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/cache/_disk_cache.py +0 -0
  20. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/cache/_redis_cache.py +0 -0
  21. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/cache/base.py +0 -0
  22. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/cache/manager.py +0 -0
  23. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/__init__.py +0 -0
  24. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/_database_config.py +0 -0
  25. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/_security_config.py +0 -0
  26. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/base.py +0 -0
  27. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/registry.py +0 -0
  28. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/config/utils.py +0 -0
  29. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/constants.py +0 -0
  30. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/contextvars.py +0 -0
  31. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/db_engine.py +0 -0
  32. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/enums.py +0 -0
  33. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/exception/__init__.py +0 -0
  34. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/exception/base.py +0 -0
  35. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/exception/exception_handler.py +0 -0
  36. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/exception/exception_manager.py +0 -0
  37. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/i18n/__init__.py +0 -0
  38. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/i18n/manager.py +0 -0
  39. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/i18n/types.py +0 -0
  40. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/i18n/utils.py +0 -0
  41. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/logging/__init__.py +0 -0
  42. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/logging/config.py +0 -0
  43. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/logging/handlers.py +0 -0
  44. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/mapper/__init__.py +0 -0
  45. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/mapper/base_mapper.py +0 -0
  46. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/mapper/impl/__init__.py +0 -0
  47. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/mapper/impl/base_mapper_impl.py +0 -0
  48. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/middleware/__init__.py +0 -0
  49. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/middleware/db_session.py +0 -0
  50. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/migrate.py +0 -0
  51. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/openapi.py +0 -0
  52. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/py.typed +0 -0
  53. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/request.py +0 -0
  54. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/response.py +0 -0
  55. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/router.py +0 -0
  56. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/schema.py +0 -0
  57. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/security/__init__.py +0 -0
  58. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/security/security.py +0 -0
  59. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/security/utils.py +0 -0
  60. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/service/__init__.py +0 -0
  61. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/service/base_service.py +0 -0
  62. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/service/impl/__init__.py +0 -0
  63. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/service/impl/base_service_impl.py +0 -0
  64. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/stream/__init__.py +0 -0
  65. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/utils/__init__.py +0 -0
  66. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/utils/excel_util.py +0 -0
  67. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/utils/file_util.py +0 -0
  68. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/utils/http_util.py +0 -0
  69. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/utils/ip_util.py +0 -0
  70. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/utils/snowflake_util.py +0 -0
  71. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib/utils/str_util.py +0 -0
  72. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib_py.egg-info/SOURCES.txt +0 -0
  73. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib_py.egg-info/dependency_links.txt +0 -0
  74. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib_py.egg-info/requires.txt +0 -0
  75. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/fastlib_py.egg-info/top_level.txt +0 -0
  76. {fastlib_py-0.2.9 → fastlib_py-0.3.2}/setup.cfg +0 -0
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 tyvekzhang
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 tyvekzhang
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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastlib-py
3
- Version: 0.2.9
3
+ Version: 0.3.2
4
4
  Summary: Fastlib, high performance, easy to use, fast to code, ready for production
5
5
  Author-email: tyvekZhang <tyvekzhang@gmail.com>
6
6
  Maintainer-email: tyvekZhang <tyvekzhang@gmail.com>
@@ -2,7 +2,6 @@
2
2
  """Fastlib Application Libraries Package."""
3
3
 
4
4
  from .config import ConfigManager as ConfigManager
5
- from .constant import constant as constant
6
5
  from .logging import LogConfig as LogConfig
7
6
  from .logging import Logger as Logger
8
7
  from .openapi import register_offline_openapi as register_offline_openapi
@@ -11,6 +10,5 @@ __all__ = [
11
10
  "ConfigManager",
12
11
  "Logger",
13
12
  "LogConfig",
14
- "constant",
15
13
  "register_offline_openapi",
16
14
  ]
@@ -19,6 +19,7 @@ class ServerConfig(BaseConfig):
19
19
  name: The server name.
20
20
  version: The server version.
21
21
  app_desc: The server description.
22
+ enable_api_prefix: Enable the API prefix for routes.
22
23
  api_prefix: The API prefix for routes.
23
24
  debug: Whether to enable debug mode.
24
25
  workers: The number of worker processes.
@@ -35,6 +36,7 @@ class ServerConfig(BaseConfig):
35
36
  app_desc: str = field(
36
37
  default_factory=lambda: ServerConfig._project_config.description
37
38
  )
39
+ enable_api_prefix: bool = False
38
40
  api_prefix: str = "/api"
39
41
  debug: bool = False
40
42
  workers: int = 1
@@ -7,7 +7,7 @@ from typing import Any, Optional
7
7
  import yaml
8
8
  from loguru import logger
9
9
 
10
- from fastlib import constant
10
+ from fastlib import constants as constant
11
11
  from fastlib.config import utils as config_util
12
12
 
13
13
 
@@ -4,14 +4,14 @@
4
4
  import os
5
5
  from typing import Any, Optional
6
6
 
7
- from fastlib import constant
7
+ from fastlib import constants as constant
8
8
  from fastlib.config import utils as config_util
9
- from fastlib.config.base import BaseConfig
10
9
  from fastlib.config._database_config import DatabaseConfig
11
- from fastlib.config.loader import ConfigLoader
12
- from fastlib.config.registry import ConfigRegistry
13
10
  from fastlib.config._security_config import SecurityConfig
14
11
  from fastlib.config._server_config import ServerConfig
12
+ from fastlib.config.base import BaseConfig
13
+ from fastlib.config.loader import ConfigLoader
14
+ from fastlib.config.registry import ConfigRegistry
15
15
 
16
16
 
17
17
  # Decorator for easy registration
@@ -5,7 +5,7 @@ import json
5
5
  from pathlib import Path
6
6
  from typing import Optional, Union
7
7
 
8
- from fastlib.constant import RESOURCE_DIR
8
+ from fastlib.constants import RESOURCE_DIR
9
9
  from fastlib.i18n.types import Language
10
10
 
11
11
  from .manager import get_language
@@ -1,40 +1,40 @@
1
- # SPDX-License-Identifier: MIT
2
- from starlette.middleware.base import BaseHTTPMiddleware
3
-
4
- from fastlib.i18n.manager import reset_language, set_language
5
- from fastlib.i18n.types import Language
6
-
7
-
8
- class I18nMiddleware(BaseHTTPMiddleware):
9
- """
10
- Middleware for automatic language detection and setting based on HTTP headers.
11
- """
12
-
13
- async def dispatch(self, request, call_next):
14
- """
15
- Process the request and set the language based on Accept-Language header.
16
-
17
- Args:
18
- request: The incoming HTTP request
19
- call_next: The next middleware or route handler in the chain
20
-
21
- Returns:
22
- The HTTP response from the next handler
23
- """
24
- # Get language preference from request headers
25
- accept_lang = request.headers.get("Accept-Language", "en")
26
-
27
- # Set the language for current request
28
- if accept_lang.startswith("en"):
29
- language = Language.CHINESE
30
- elif accept_lang.startswith("zh"):
31
- language = Language.CHINESE
32
-
33
- set_language(language)
34
- try:
35
- response = await call_next(request)
36
- finally:
37
- # Always reset to prevent leaking context between requests
38
- reset_language()
39
-
40
- return response
1
+ # SPDX-License-Identifier: MIT
2
+ from starlette.middleware.base import BaseHTTPMiddleware
3
+
4
+ from fastlib.i18n.manager import reset_language, set_language
5
+ from fastlib.i18n.types import Language
6
+
7
+
8
+ class I18nMiddleware(BaseHTTPMiddleware):
9
+ """
10
+ Middleware for automatic language detection and setting based on HTTP headers.
11
+ """
12
+
13
+ async def dispatch(self, request, call_next):
14
+ """
15
+ Process the request and set the language based on Accept-Language header.
16
+
17
+ Args:
18
+ request: The incoming HTTP request
19
+ call_next: The next middleware or route handler in the chain
20
+
21
+ Returns:
22
+ The HTTP response from the next handler
23
+ """
24
+ # Get language preference from request headers
25
+ accept_lang = request.headers.get("Accept-Language", "en")
26
+
27
+ # Set the language for current request
28
+ if accept_lang.startswith("en"):
29
+ language = Language.CHINESE
30
+ elif accept_lang.startswith("zh"):
31
+ language = Language.CHINESE
32
+
33
+ set_language(language)
34
+ try:
35
+ response = await call_next(request)
36
+ finally:
37
+ # Always reset to prevent leaking context between requests
38
+ reset_language()
39
+
40
+ return response
@@ -9,7 +9,8 @@ from jwt.exceptions import PyJWTError
9
9
  from loguru import logger
10
10
  from starlette.responses import JSONResponse
11
11
 
12
- from fastlib import ConfigManager, constant, security
12
+ from fastlib import ConfigManager, security
13
+ from fastlib import constants as constant
13
14
  from fastlib.contextvars import clear_current_user, set_current_user
14
15
  from fastlib.enums import MediaTypeEnum
15
16
  from fastlib.schema import UserCredential
@@ -1,36 +1,36 @@
1
- # SPDX-License-Identifier: MIT
2
- """
3
- Enums for stream module
4
- """
5
-
6
- from enum import Enum
7
-
8
-
9
- class MessageRole(str, Enum):
10
- """Message role enumeration"""
11
-
12
- SYSTEM = "system"
13
- USER = "user"
14
- ASSISTANT = "assistant"
15
- FUNCTION = "function"
16
-
17
-
18
- class MessageStatus(str, Enum):
19
- """Message status enumeration"""
20
-
21
- CREATED = "created"
22
- RUNNING = "running"
23
- COMPLETED = "completed"
24
- FAILED = "failed"
25
- CANCELLED = "cancelled"
26
-
27
-
28
- class StreamEventType(str, Enum):
29
- """Stream event type"""
30
-
31
- START = "start"
32
- CONTENT = "content"
33
- FUNCTION_CALL = "function_call"
34
- ERROR = "error"
35
- END = "end"
36
- METADATA = "metadata"
1
+ # SPDX-License-Identifier: MIT
2
+ """
3
+ Enums for stream module
4
+ """
5
+
6
+ from enum import Enum
7
+
8
+
9
+ class MessageRole(str, Enum):
10
+ """Message role enumeration"""
11
+
12
+ SYSTEM = "system"
13
+ USER = "user"
14
+ ASSISTANT = "assistant"
15
+ FUNCTION = "function"
16
+
17
+
18
+ class MessageStatus(str, Enum):
19
+ """Message status enumeration"""
20
+
21
+ CREATED = "created"
22
+ RUNNING = "running"
23
+ COMPLETED = "completed"
24
+ FAILED = "failed"
25
+ CANCELLED = "cancelled"
26
+
27
+
28
+ class StreamEventType(str, Enum):
29
+ """Stream event type"""
30
+
31
+ START = "start"
32
+ CONTENT = "content"
33
+ FUNCTION_CALL = "function_call"
34
+ ERROR = "error"
35
+ END = "end"
36
+ METADATA = "metadata"
@@ -1,101 +1,101 @@
1
- # SPDX-License-Identifier: MIT
2
- """
3
- Copy from https://github.com/sysid/sse-starlette/blob/main/sse_starlette/event.py
4
- """
5
-
6
- import io
7
- import json
8
- import re
9
- from typing import Any, Optional, Union
10
-
11
-
12
- class ServerSentEvent:
13
- """
14
- Helper class to format data for Server-Sent Events (SSE).
15
- """
16
-
17
- _LINE_SEP_EXPR = re.compile(r"\r\n|\r|\n")
18
- DEFAULT_SEPARATOR = "\r\n"
19
-
20
- def __init__(
21
- self,
22
- data: Optional[Any] = None,
23
- *,
24
- event: Optional[str] = None,
25
- id: Optional[str] = None,
26
- retry: Optional[int] = None,
27
- comment: Optional[str] = None,
28
- sep: Optional[str] = None,
29
- ) -> None:
30
- self.data = data
31
- self.event = event
32
- self.id = id
33
- self.retry = retry
34
- self.comment = comment
35
- self._sep = sep if sep is not None else self.DEFAULT_SEPARATOR
36
-
37
- def encode(self) -> bytes:
38
- buffer = io.StringIO()
39
- if self.comment is not None:
40
- for chunk in self._LINE_SEP_EXPR.split(str(self.comment)):
41
- buffer.write(f": {chunk}{self._sep}")
42
-
43
- if self.id is not None:
44
- # Clean newlines in the event id
45
- buffer.write("id: " + self._LINE_SEP_EXPR.sub("", self.id) + self._sep)
46
-
47
- if self.event is not None:
48
- # Clean newlines in the event name
49
- buffer.write(
50
- "event: " + self._LINE_SEP_EXPR.sub("", self.event) + self._sep
51
- )
52
-
53
- if self.data is not None:
54
- # Break multi-line data into multiple data: lines
55
- for chunk in self._LINE_SEP_EXPR.split(str(self.data)):
56
- buffer.write(f"data: {chunk}{self._sep}")
57
-
58
- if self.retry is not None:
59
- if not isinstance(self.retry, int):
60
- raise TypeError("retry argument must be int")
61
- buffer.write(f"retry: {self.retry}{self._sep}")
62
-
63
- buffer.write(self._sep)
64
- return buffer.getvalue().encode("utf-8")
65
-
66
-
67
- class JSONServerSentEvent(ServerSentEvent):
68
- """
69
- Helper class to format JSON data for Server-Sent Events (SSE).
70
- """
71
-
72
- def __init__(
73
- self,
74
- data: Optional[Any] = None,
75
- *args,
76
- **kwargs,
77
- ) -> None:
78
- super().__init__(
79
- json.dumps(
80
- data,
81
- ensure_ascii=False,
82
- allow_nan=False,
83
- indent=None,
84
- separators=(",", ":"),
85
- )
86
- if data is not None
87
- else None,
88
- *args,
89
- **kwargs,
90
- )
91
-
92
-
93
- def ensure_bytes(data: Union[bytes, dict, ServerSentEvent, Any], sep: str) -> bytes:
94
- if isinstance(data, bytes):
95
- return data
96
- if isinstance(data, ServerSentEvent):
97
- return data.encode()
98
- if isinstance(data, dict):
99
- data["sep"] = sep
100
- return ServerSentEvent(**data).encode()
101
- return ServerSentEvent(str(data), sep=sep).encode()
1
+ # SPDX-License-Identifier: MIT
2
+ """
3
+ Copy from https://github.com/sysid/sse-starlette/blob/main/sse_starlette/event.py
4
+ """
5
+
6
+ import io
7
+ import json
8
+ import re
9
+ from typing import Any, Optional, Union
10
+
11
+
12
+ class ServerSentEvent:
13
+ """
14
+ Helper class to format data for Server-Sent Events (SSE).
15
+ """
16
+
17
+ _LINE_SEP_EXPR = re.compile(r"\r\n|\r|\n")
18
+ DEFAULT_SEPARATOR = "\r\n"
19
+
20
+ def __init__(
21
+ self,
22
+ data: Optional[Any] = None,
23
+ *,
24
+ event: Optional[str] = None,
25
+ id: Optional[str] = None,
26
+ retry: Optional[int] = None,
27
+ comment: Optional[str] = None,
28
+ sep: Optional[str] = None,
29
+ ) -> None:
30
+ self.data = data
31
+ self.event = event
32
+ self.id = id
33
+ self.retry = retry
34
+ self.comment = comment
35
+ self._sep = sep if sep is not None else self.DEFAULT_SEPARATOR
36
+
37
+ def encode(self) -> bytes:
38
+ buffer = io.StringIO()
39
+ if self.comment is not None:
40
+ for chunk in self._LINE_SEP_EXPR.split(str(self.comment)):
41
+ buffer.write(f": {chunk}{self._sep}")
42
+
43
+ if self.id is not None:
44
+ # Clean newlines in the event id
45
+ buffer.write("id: " + self._LINE_SEP_EXPR.sub("", self.id) + self._sep)
46
+
47
+ if self.event is not None:
48
+ # Clean newlines in the event name
49
+ buffer.write(
50
+ "event: " + self._LINE_SEP_EXPR.sub("", self.event) + self._sep
51
+ )
52
+
53
+ if self.data is not None:
54
+ # Break multi-line data into multiple data: lines
55
+ for chunk in self._LINE_SEP_EXPR.split(str(self.data)):
56
+ buffer.write(f"data: {chunk}{self._sep}")
57
+
58
+ if self.retry is not None:
59
+ if not isinstance(self.retry, int):
60
+ raise TypeError("retry argument must be int")
61
+ buffer.write(f"retry: {self.retry}{self._sep}")
62
+
63
+ buffer.write(self._sep)
64
+ return buffer.getvalue().encode("utf-8")
65
+
66
+
67
+ class JSONServerSentEvent(ServerSentEvent):
68
+ """
69
+ Helper class to format JSON data for Server-Sent Events (SSE).
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ data: Optional[Any] = None,
75
+ *args,
76
+ **kwargs,
77
+ ) -> None:
78
+ super().__init__(
79
+ json.dumps(
80
+ data,
81
+ ensure_ascii=False,
82
+ allow_nan=False,
83
+ indent=None,
84
+ separators=(",", ":"),
85
+ )
86
+ if data is not None
87
+ else None,
88
+ *args,
89
+ **kwargs,
90
+ )
91
+
92
+
93
+ def ensure_bytes(data: Union[bytes, dict, ServerSentEvent, Any], sep: str) -> bytes:
94
+ if isinstance(data, bytes):
95
+ return data
96
+ if isinstance(data, ServerSentEvent):
97
+ return data.encode()
98
+ if isinstance(data, dict):
99
+ data["sep"] = sep
100
+ return ServerSentEvent(**data).encode()
101
+ return ServerSentEvent(str(data), sep=sep).encode()