channels-extensions 0.0.1__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.
File without changes
@@ -0,0 +1,10 @@
1
+ import sys
2
+
3
+ if sys.version_info >= (3, 12):
4
+ from typing import override
5
+ else:
6
+ from typing_extensions import override
7
+
8
+ __all__ = [
9
+ "override",
10
+ ]
@@ -0,0 +1,25 @@
1
+ from typing import Any
2
+
3
+ import orjson
4
+ from channels.generic import websocket
5
+ from django_orjson import default
6
+
7
+
8
+ class JsonWebsocketConsumer(websocket.JsonWebsocketConsumer):
9
+ @classmethod
10
+ def decode_json(cls, text_data) -> Any:
11
+ return orjson.loads(text_data)
12
+
13
+ @classmethod
14
+ def encode_json(cls, content) -> str:
15
+ return orjson.dumps(content).decode()
16
+
17
+
18
+ class AsyncJsonWebsocketConsumer(websocket.AsyncJsonWebsocketConsumer):
19
+ @classmethod
20
+ async def decode_json(cls, text_data) -> Any:
21
+ return orjson.loads(text_data)
22
+
23
+ @classmethod
24
+ async def encode_json(cls, content) -> str:
25
+ return orjson.dumps(content, default=default).decode()
@@ -0,0 +1,95 @@
1
+ import re
2
+ from typing import Any
3
+
4
+ from asyncio_extensions import checkpoint, sleep_forever
5
+ from channels import DEFAULT_CHANNEL_LAYER
6
+ from channels.layers import BaseChannelLayer
7
+ from channels.layers import get_channel_layer as original_get_channel_layer
8
+ from django.core.exceptions import ImproperlyConfigured
9
+ from django.utils.crypto import get_random_string
10
+
11
+ from ._compat import override
12
+
13
+
14
+ class DummyChannelLayer(BaseChannelLayer):
15
+ """Dummy channel layer implementation.
16
+
17
+ This is a no-op channel layer. It never send or receive any message.
18
+ """
19
+
20
+ extensions = ["groups", "flush"] # noqa: RUF012
21
+
22
+ def __init__(
23
+ self,
24
+ expiry: int = 60,
25
+ capacity: int = 100,
26
+ channel_capacity: dict[re.Pattern[str] | str, int] | None = None,
27
+ ) -> None:
28
+ super().__init__(expiry, capacity, channel_capacity)
29
+
30
+ @override
31
+ async def send(self, channel: str, message: dict[str, Any]) -> None: # noqa: ARG002
32
+ """
33
+ Send a message onto a (general or specific) channel.
34
+
35
+ Do nothing.
36
+ """
37
+ await checkpoint()
38
+
39
+ @override
40
+ async def receive(self, channel: str) -> dict[str, Any]: # noqa: ARG002
41
+ """
42
+ Receive the first message that arrives on the channel.
43
+
44
+ Never returns.
45
+ """
46
+ await sleep_forever()
47
+
48
+ @override
49
+ async def new_channel(self, prefix: str = "specific") -> str:
50
+ """
51
+ Returns a new channel name that can be used by something in our
52
+ process as a specific channel.
53
+ """
54
+ return f"{prefix}.null!{get_random_string(12)}"
55
+
56
+ @override
57
+ async def flush(self) -> None:
58
+ """Resets the channel layer to a blank state."""
59
+ await checkpoint()
60
+
61
+ @override
62
+ async def group_add(self, group: str, channel: str) -> None: # noqa: ARG002
63
+ """Add a channel to the group."""
64
+ await checkpoint()
65
+
66
+ @override
67
+ async def group_discard(self, group: str, channel: str) -> None: # noqa: ARG002
68
+ """Remove the channel from the group."""
69
+ await checkpoint()
70
+
71
+ @override
72
+ async def group_send(self, group: str, message: dict[str, Any]) -> None: # noqa: ARG002
73
+ """Send a message to the group."""
74
+ await checkpoint()
75
+
76
+
77
+ def get_channel_layer(alias: str = DEFAULT_CHANNEL_LAYER) -> BaseChannelLayer:
78
+ """Returns a channel layer by alias.
79
+
80
+ This is a wrapper around :func:`channels.layers.get_channel_layer` that throws an error for
81
+ invalid aliases.
82
+
83
+ Returns:
84
+ The channel layer.
85
+
86
+ Raises:
87
+ ImproperlyConfigured: when the alias is invalid.
88
+ """
89
+ channel_layer: BaseChannelLayer | None = original_get_channel_layer(alias)
90
+
91
+ if not channel_layer:
92
+ msg: str = "{alias} isn't an available channel layer"
93
+ raise ImproperlyConfigured(msg)
94
+
95
+ return channel_layer
File without changes
@@ -0,0 +1,26 @@
1
+ import asyncio
2
+ from copy import copy
3
+ from typing import Any
4
+
5
+ from asgiref.typing import ASGIApplication, ASGIReceiveCallable, ASGISendCallable
6
+ from channels.db import database_sync_to_async
7
+ from channels.middleware import BaseMiddleware
8
+ from django.contrib.sites.models import Site
9
+
10
+
11
+ class CurrentSiteMiddleware(BaseMiddleware):
12
+ """
13
+ Middleware that adds the current Site object to the scope.
14
+ """
15
+
16
+ def __init__(self, inner: ASGIApplication) -> None:
17
+ super().__init__(inner)
18
+ self._lock = asyncio.Lock()
19
+
20
+ async def __call__(self, scope: dict[str, Any], receive: ASGIReceiveCallable, send: ASGISendCallable) -> Any: # type: ignore[override]
21
+ if "site" not in scope:
22
+ async with self._lock:
23
+ if "site" not in scope:
24
+ scope = copy(scope)
25
+ scope["site"] = await database_sync_to_async(Site.objects.get_current)()
26
+ return await super().__call__(scope, receive, send) # type: ignore[arg-type]
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: channels-extensions
3
+ Version: 0.0.1
4
+ Summary: Some extensions for Django Channels.
5
+ Project-URL: Documentation, https://github.com/hartungstenio/channels-extensions#readme
6
+ Project-URL: Issues, https://github.com/hartungstenio/channels-extensions/issues
7
+ Project-URL: Source, https://github.com/hartungstenio/channels-extensions
8
+ Author-email: Christian Hartung <6785871+hartungstenio@users.noreply.github.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE.txt
11
+ Keywords: django
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: Django :: 5.2
14
+ Classifier: Framework :: Django :: 6.0
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: asgiref
24
+ Requires-Dist: asyncio-extensions
25
+ Requires-Dist: channels
26
+ Requires-Dist: django>=5.2
27
+ Requires-Dist: typing-extensions; python_version < '3.12'
28
+ Provides-Extra: orjson
29
+ Requires-Dist: django-orjson; extra == 'orjson'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # channels-extensions
33
+
34
+ [![PyPI - Version](https://img.shields.io/pypi/v/channels-extensions.svg)](https://pypi.org/project/channels-extensions)
35
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/channels-extensions.svg)](https://pypi.org/project/channels-extensions)
36
+
37
+ -----
38
+
39
+ ## Installation
40
+
41
+ ```console
42
+ pip install channels-extensions
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ### DummyChannelLayer
48
+ ```DummyChannelLayer``` is an noop (almost) implementation of `BaseChannelLayer`. Messages sent to it are never available, and `receive` never returns.
49
+
50
+ All methods work as checkpoints to the event loop, yielding control back to it at least once.
51
+
52
+ ```python
53
+ CHANNEL_LAYERS = {
54
+ "dummy": {
55
+ "BACKEND": "channels_extensions.layers.DummyChannelLayer",
56
+ }
57
+ }
58
+ ```
59
+
60
+ ### get_channel_layer
61
+ This is simply a version of channels `get_channel_layer`, but it raises an `ImproperlyConfigured` if the alias does not exist.
62
+
63
+ ### CurrentSiteMiddleware
64
+ A middleware that mimics django's `CurrentSiteMiddleware`. It adds a `site` key to the scope:
65
+ ```python
66
+ class EchoSiteConsumer(AsyncConsumer):
67
+ async def websocket_connect(self, event):
68
+ await self.send({
69
+ "type": "websocket.accept",
70
+ })
71
+
72
+ async def websocket_receive(self, event):
73
+ await self.send({
74
+ "type": "websocket.send",
75
+ "text": self.scope["site"],
76
+ })
77
+
78
+ application = ProtocolTypeRouter({
79
+ "websocket": AllowedHostsOriginValidator(
80
+ AuthMiddlewareStack(
81
+ CurrentSiteMiddleware(
82
+ URLRouter([
83
+ path("echo/", EchoSiteConsumer.as_asgi()),
84
+ ])
85
+ )
86
+ )
87
+ ),
88
+ })
89
+ ```
90
+
91
+ ## License
92
+
93
+ `channels-extensions` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.
@@ -0,0 +1,10 @@
1
+ channels_extensions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ channels_extensions/_compat.py,sha256=v53C3PPEW7pq7wDTtFQbMKH5RplQn2p5LzHVU-NqJ_M,156
3
+ channels_extensions/consumers.py,sha256=CrK7d7GtG7DWFOQnD2OKzXwIpVmGp84msI4YBvLgPNU,690
4
+ channels_extensions/layers.py,sha256=6A8Wq3LahsKPFHXnizuoR19Q7npkv8yIV6YKAX91qT0,2842
5
+ channels_extensions/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ channels_extensions/sites.py,sha256=D-AvkKpTMQJXxi7vxGd1-Oiaz6WTUEAXVQmKxRKupUU,1000
7
+ channels_extensions-0.0.1.dist-info/METADATA,sha256=18JAwvnOtUQXhudEJeTXXS4jIcgOLH10QxHen179ycs,3091
8
+ channels_extensions-0.0.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
9
+ channels_extensions-0.0.1.dist-info/licenses/LICENSE.txt,sha256=bi3N4z7mSg41vy86zZ0psD6sHeOfupfusDTsBEF5HO4,1131
10
+ channels_extensions-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present Christian Hartung <6785871+hartungstenio@users.noreply.github.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.