pydantic-socketio 0.1.0__py3-none-any.whl

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,16 @@
1
+ # first import everything from socketio
2
+ from socketio import * # type: ignore # noqa: F403
3
+
4
+ from .pydantic_socketio import (
5
+ BaseClient as BaseClient,
6
+ Client as Client,
7
+ AsyncClient as AsyncClient,
8
+ BaseServer as BaseServer,
9
+ Server as Server,
10
+ AsyncServer as AsyncServer,
11
+ monkey_patch as monkey_patch,
12
+ )
13
+
14
+ from .fastapi_socketio import (
15
+ FastAPISocketIO as FastAPISocketIO,
16
+ )
@@ -0,0 +1,40 @@
1
+ from typing import TYPE_CHECKING, Optional
2
+
3
+ if TYPE_CHECKING:
4
+ from fastapi import FastAPI
5
+
6
+ from . import AsyncServer, ASGIApp
7
+
8
+
9
+ class FastAPISocketIO(AsyncServer):
10
+ """
11
+ Pydantic SocketIO server for FastAPI. This class is a subclass of AsyncServer
12
+ and is used to create a SocketIO server that can be mounted on a FastAPI app.
13
+ It also adds `sio` to the FastAPI app state.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ app: Optional["FastAPI"] = None,
19
+ socketio_path: str = "socket.io",
20
+ **kwargs,
21
+ ) -> None:
22
+ # disable socketio CORS handling and let fastapi CORS handle it
23
+ super().__init__(cors_allowed_origins=[], async_mode="asgi", **kwargs)
24
+ self.socketio_path = socketio_path
25
+ if app:
26
+ self.integrate(app)
27
+
28
+ def integrate(self, app: "FastAPI"):
29
+ """Integrate the FastAPISocketIO server with a FastAPI app."""
30
+ try:
31
+ from fastapi import FastAPI
32
+ except ImportError:
33
+ raise ImportError(
34
+ "FastAPI is not installed. Please install FastAPI to use FastAPISocketIO."
35
+ )
36
+ assert isinstance(app, FastAPI), "app must be a FastAPI instance"
37
+ self.sio_app = ASGIApp(socketio_server=self, socketio_path=self.socketio_path)
38
+ app.mount("/" + self.socketio_path, self.sio_app)
39
+ app.state.sio = self
40
+ self.fastapi_app = app
File without changes
@@ -0,0 +1,174 @@
1
+ import functools
2
+ import inspect
3
+ import logging
4
+ from typing import Any, Callable, Optional, Union
5
+
6
+ from pydantic import validate_call, ValidationError
7
+ from pydantic_core import to_jsonable_python
8
+ from socketio import (
9
+ AsyncServer as OldAsyncServer,
10
+ Server as OldServer,
11
+ Client as OldClient,
12
+ AsyncClient as OldAsyncClient,
13
+ )
14
+ from socketio.base_server import BaseServer as OldBaseServer
15
+ from socketio.base_client import BaseClient as OldBaseClient
16
+
17
+
18
+ # Save the original functions
19
+ _old_server_on = OldBaseServer.on
20
+ _old_server_emit = OldServer.emit
21
+ _old_server_emit_async = OldAsyncServer.emit
22
+ _old_client_on = OldBaseClient.on
23
+ _old_client_emit = OldClient.emit
24
+ _old_client_emit_async = OldAsyncClient.emit
25
+
26
+
27
+ module_logger = logging.getLogger(__name__)
28
+ module_logger.addHandler(logging.NullHandler())
29
+
30
+
31
+ def _wrapper(
32
+ handler: Callable,
33
+ old_on: Callable,
34
+ self: Union[OldBaseClient, OldBaseServer],
35
+ event: str,
36
+ *args,
37
+ **kwargs,
38
+ ):
39
+ """Wrap the handler to validate the input using pydantic"""
40
+ validated_handler = validate_call(handler)
41
+ if event in ["connect", "disconnect"]:
42
+ # For connect and disconnect events, convert ValidationError
43
+ # to TypeError, so that socketio can handle it properly
44
+ if inspect.iscoroutinefunction(validated_handler):
45
+
46
+ @functools.wraps(validated_handler)
47
+ async def wrapped_handler(*args, **kwargs): # type: ignore
48
+ try:
49
+ return await validated_handler(*args, **kwargs)
50
+ except ValidationError as e:
51
+ raise TypeError from e
52
+ else:
53
+
54
+ @functools.wraps(validated_handler)
55
+ def wrapped_handler(*args, **kwargs):
56
+ try:
57
+ return validated_handler(*args, **kwargs)
58
+ except ValidationError as e:
59
+ raise TypeError from e
60
+ else:
61
+ wrapped_handler = validated_handler # type: ignore
62
+
63
+ # Register the wrapped handler
64
+ old_on(self, event, wrapped_handler, *args, **kwargs)
65
+ return wrapped_handler
66
+
67
+
68
+ class BaseServer(OldBaseServer):
69
+ """BaseServer with pydantic validation."""
70
+
71
+ def on(
72
+ self: OldBaseServer,
73
+ event: str,
74
+ handler: Optional[Callable] = None,
75
+ *args,
76
+ **kwargs,
77
+ ) -> Callable:
78
+ if handler is None:
79
+ # invoked as a decorator
80
+ return functools.partial(
81
+ _wrapper,
82
+ old_on=_old_server_on,
83
+ self=self,
84
+ event=event,
85
+ *args,
86
+ **kwargs,
87
+ )
88
+ else:
89
+ # not invoked as a decorator, but as a function
90
+ return _wrapper(handler, _old_server_on, self, event, *args, **kwargs)
91
+
92
+
93
+ class Server(BaseServer, OldServer):
94
+ """Server with pydantic validation and data conversion."""
95
+
96
+ def emit(
97
+ self: OldServer,
98
+ event: str,
99
+ data: Any = None,
100
+ to: Optional[str] = None,
101
+ *args,
102
+ **kwargs,
103
+ ):
104
+ return _old_server_emit(
105
+ self, event=event, data=to_jsonable_python(data), to=to, *args, **kwargs
106
+ )
107
+
108
+
109
+ class AsyncServer(BaseServer, OldAsyncServer):
110
+ """AsyncServer with pydantic validation and data conversion."""
111
+
112
+ async def emit(
113
+ self: OldAsyncServer,
114
+ event: str,
115
+ data: Any = None,
116
+ to: Optional[str] = None,
117
+ *args,
118
+ **kwargs,
119
+ ):
120
+ return await _old_server_emit_async(
121
+ self, event=event, data=to_jsonable_python(data), to=to, *args, **kwargs
122
+ )
123
+
124
+
125
+ class BaseClient(OldBaseClient):
126
+ """BaseClient with pydantic validation."""
127
+
128
+ def on(
129
+ self: OldBaseClient,
130
+ event: str,
131
+ handler: Optional[Callable] = None,
132
+ *args,
133
+ **kwargs,
134
+ ) -> Callable:
135
+ if handler is None:
136
+ # invoked as a decorator
137
+ return functools.partial(
138
+ _wrapper,
139
+ old_on=_old_client_on,
140
+ self=self,
141
+ event=event,
142
+ *args,
143
+ **kwargs,
144
+ )
145
+ else:
146
+ # not invoked as a decorator, but as a function
147
+ return _wrapper(handler, _old_client_on, self, event, *args, **kwargs)
148
+
149
+
150
+ class Client(BaseClient, OldClient):
151
+ """Client with pydantic validation and data conversion."""
152
+
153
+ def emit(self: OldClient, event: str, data: Any = None, *args, **kwargs):
154
+ return _old_client_emit(self, event, to_jsonable_python(data), *args, **kwargs)
155
+
156
+
157
+ class AsyncClient(BaseClient, OldAsyncClient):
158
+ """AsyncClient with pydantic validation and data conversion."""
159
+
160
+ async def emit(self: OldAsyncClient, event: str, data: Any = None, *args, **kwargs):
161
+ return await _old_client_emit_async(
162
+ self, event, to_jsonable_python(data), *args, **kwargs
163
+ )
164
+
165
+
166
+ def monkey_patch():
167
+ module_logger.debug("Monkey patching")
168
+ OldBaseServer.on = BaseServer.on
169
+ OldServer.emit = Server.emit
170
+ OldAsyncServer.emit = AsyncServer.emit
171
+ OldBaseClient.on = BaseClient.on
172
+ OldClient.emit = Client.emit
173
+ OldAsyncClient.emit = AsyncClient.emit
174
+ module_logger.debug("Monkey patched")
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.4
2
+ Name: pydantic-socketio
3
+ Version: 0.1.0
4
+ Summary: Pydantic-enhanced SocketIO with FastAPI integration support.
5
+ Project-URL: homepage, https://github.com/atomiechen/Pydantic-SocketIO
6
+ Project-URL: issues, https://github.com/atomiechen/Pydantic-SocketIO/issues
7
+ Project-URL: changelog, https://github.com/atomiechen/Pydantic-SocketIO/blob/main/CHANGELOG.md
8
+ Author-email: Atomie CHEN <atomic_cwh@163.com>
9
+ License-File: LICENSE
10
+ Keywords: fastapi,pydantic,socketio
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.8
15
+ Requires-Dist: pydantic>=2.10.6
16
+ Requires-Dist: python-socketio>=5.12.1
17
+ Provides-Extra: asyncio-client
18
+ Requires-Dist: python-socketio[asyncio-client]>=5.12.1; extra == 'asyncio-client'
19
+ Provides-Extra: client
20
+ Requires-Dist: python-socketio[client]>=5.12.1; extra == 'client'
21
+ Provides-Extra: docs
22
+ Requires-Dist: python-socketio[docs]>=5.12.1; extra == 'docs'
23
+ Provides-Extra: fastapi
24
+ Requires-Dist: fastapi[standard]>=0.115.11; extra == 'fastapi'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Pydantic-SocketIO
28
+
29
+ A Pydantic-enhanced SocketIO library for Python, with FastAPI integration.
30
+
31
+
32
+ ## Features
33
+
34
+ ⭐️ **Pydantic-Enhanced SocketIO**: Drop-in replacements for the original [python-socketio](https://github.com/miguelgrinberg/python-socketio) server and client (sync and async), with built-in Pydantic validation for event data. You can also easily monkey patch this validation to the original `socketio` server and client.
35
+
36
+ 🪐 **Easy Integration with FastAPI**: Seamlessly integrates `Socket.IO` with FastAPI, allowing you to manage event-driven communication effortlessly.
37
+
38
+
39
+ ## Installation
40
+
41
+ ```sh
42
+ pip install pydantic-socketio
43
+ ```
44
+
45
+
46
+ ## Usage
47
+
48
+ ### Recommended: Pydantic-Enhanced SocketIO Server and Client
49
+
50
+ Drop-in replacements for the original [python-socketio](https://github.com/miguelgrinberg/python-socketio) server and client are provided.
51
+
52
+ The enhanced SocketIO server with Pydantic validation:
53
+
54
+ ```python
55
+ from pydantic import BaseModel
56
+ import pydantic_socketio
57
+
58
+ class ChatMessage(BaseModel):
59
+ role: str
60
+ content: str
61
+
62
+ # Create an enhanced SocketIO server; use AsyncServer for async server
63
+ sio = pydantic_socketio.Server()
64
+
65
+ # Define an event with Pydantic validation
66
+ @sio.event
67
+ def message(data: ChatMessage):
68
+ print(f"Received chat message from {data.role}: {data.content}")
69
+ data.content = data.content.upper()
70
+ print(f"Sending uppercase message: {data.content}")
71
+ # Emit an event with Pydantic model without any additional conversion
72
+ sio.emit("message", data)
73
+
74
+ # `on` decorator is also supported
75
+ @sio.on("custom_event")
76
+ def handle_custom_event(data: int):
77
+ ...
78
+ ```
79
+
80
+ The enhanced SocketIO client with Pydantic validation:
81
+
82
+ ```python
83
+ import pydantic_socketio
84
+
85
+ # Create an enhanced SocketIO client; use AsyncClient for async client
86
+ sio = pydantic_socketio.Client()
87
+
88
+ @sio.event
89
+ def ping(data: int):
90
+ ...
91
+
92
+ @sio.on("pong")
93
+ def handle_pong(data: int):
94
+ ...
95
+ ```
96
+
97
+
98
+ ### Alternative: Monkey Patching for Original SocketIO
99
+
100
+ Alternatively, if you want to apply Pydantic validation to the original [python-socketio](https://github.com/miguelgrinberg/python-socketio) server and client without replacing them, you can use the `monkey_patch()` method:
101
+
102
+ ```python
103
+ from pydantic_socketio import monkey_patch
104
+ import socketio
105
+
106
+ # Apply monkey patch to the original socketio server and client
107
+ monkey_patch()
108
+
109
+ # Now, you can use the original socketio server and client with Pydantic validation
110
+ sio = socketio.Server()
111
+
112
+ @sio.event
113
+ def ping(data: int):
114
+ print(f"Received ping: {data}")
115
+ data += 1
116
+ print(f"Sending pong: {data}")
117
+ sio.emit("poing", data)
118
+ ```
119
+
120
+
121
+ ### FastAPI Integration
122
+
123
+ You can easily integrate the enhanced socketio server with FastAPI by using FastAPISocketIO:
124
+
125
+ ```python
126
+ from fastapi import FastAPI
127
+ from pydantic_socketio import FastAPISocketIO
128
+
129
+ app = FastAPI()
130
+
131
+ @app.get("/")
132
+ async def root():
133
+ return {"message": "Hello World"}
134
+ ...
135
+
136
+ # Create a FastAPI socketio server
137
+ sio = FastAPISocketIO(app)
138
+
139
+ @sio.event
140
+ async def ping(data: int):
141
+ print(f"Received ping: {data}")
142
+ data += 1
143
+ print(f"Sending pong: {data}")
144
+ await sio.emit("pong", data)
145
+ ...
146
+ ```
147
+
148
+ You can also integrate the SocketIO server manually after FastAPI initialization:
149
+
150
+ ```python
151
+ from fastapi import FastAPI
152
+ from pydantic_socketio import FastAPISocketIO
153
+
154
+ sio = FastAPISocketIO()
155
+ ...
156
+ app = FastAPI()
157
+ ...
158
+
159
+ # Integrate the SocketIO server to FastAPI
160
+ sio.integrate(app)
161
+ ```
162
+
163
+ ## License
164
+
165
+ [Pydantic-SocketIO](https://github.com/atomiechen/Pydantic-SocketIO) © 2025 by [Atomie CHEN](https://github.com/atomiechen) is licensed under the [MIT License](https://github.com/atomiechen/Pydantic-SocketIO/blob/main/LICENSE).
@@ -0,0 +1,8 @@
1
+ pydantic_socketio/__init__.py,sha256=Sl-HYhhteo4mFOIU2xc2bw341hAnnj5ZfpD1VMpr5mc,405
2
+ pydantic_socketio/fastapi_socketio.py,sha256=OcwzFzZTnoKqpCGX7SyaBYqq2rL3MCKgRQXURM3Yt30,1397
3
+ pydantic_socketio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ pydantic_socketio/pydantic_socketio.py,sha256=EVFQitiDaoB_aDm4iNHsVSK_TF1q5BBRAAQgjo8qYiM,5202
5
+ pydantic_socketio-0.1.0.dist-info/METADATA,sha256=5NRp_PspYZTHwCgMkcCaEIHE1acF7BWvgC61IrD1a1U,4787
6
+ pydantic_socketio-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ pydantic_socketio-0.1.0.dist-info/licenses/LICENSE,sha256=SpSDGxJCTumVhMVOPkFg_x6q01lPcU6KsYh_7DhwJg0,1068
8
+ pydantic_socketio-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Atomie CHEN
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.