drf-spectacular-websocket


Namedrf-spectacular-websocket JSON
Version 1.2.7 PyPI version JSON
download
home_pagehttps://github.com/Friskes/drf-spectacular-websocket
SummaryExtend websocket schema decorator for Django Channels
upload_time2024-05-02 17:18:47
maintainerNone
docs_urlNone
authorFriskes
requires_python>=3.8
licenseMIT License Copyright (c) 2024 Friskes 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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.
keywords django drf spectacular swagger channels
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Extend websocket schema decorator for Django Channels

<div align="center">

| Project   |     | Status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|-----------|:----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| CI/CD     |     | [![Latest Release](https://github.com/Friskes/drf-spectacular-websocket/actions/workflows/publish-to-pypi.yml/badge.svg)](https://github.com/Friskes/drf-spectacular-websocket/actions/workflows/publish-to-pypi.yml)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Quality   |     | [![Coverage](https://codecov.io/github/Friskes/drf-spectacular-websocket/graph/badge.svg?token=vKez4Pycrc)](https://codecov.io/github/Friskes/drf-spectacular-websocket)                                                                                                                                                                                                                                                                                                                               |
| Package   |     | [![PyPI - Version](https://img.shields.io/pypi/v/drf-spectacular-websocket?labelColor=202235&color=edb641&logo=python&logoColor=edb641)](https://badge.fury.io/py/drf-spectacular-websocket) ![PyPI - Support Python Versions](https://img.shields.io/pypi/pyversions/drf-spectacular-websocket?labelColor=202235&color=edb641&logo=python&logoColor=edb641) ![Project PyPI - Downloads](https://img.shields.io/pypi/dm/drf-spectacular-websocket?logo=python&label=downloads&labelColor=202235&color=edb641&logoColor=edb641)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Meta      |     | [![types - Mypy](https://img.shields.io/badge/types-Mypy-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://github.com/python/mypy) [![License - MIT](https://img.shields.io/badge/license-MIT-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://spdx.org/licenses/) [![code style - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/format.json&labelColor=202235)](https://github.com/astral-sh/ruff) |

</div>

> Provides [extend_ws_schema](#About-decorator) decorator to documentation [Cunsumer](https://channels.readthedocs.io/en/latest/topics/consumers.html) methods from [channels](https://github.com/django/channels) just like it does [drf-spectacular](https://github.com/tfranzel/drf-spectacular)


## Install
1. Install package
    ```bash
    pip install drf-spectacular-websocket
    ```

2. Create sidecar static
    ```bash
    python manage.py collectstatic
    ```

3. Add app name to `INSTALLED_APPS`
    > `drf_spectacular_websocket` must be higher than `drf_spectacular`
    ```python
    INSTALLED_APPS = [
        'drf_spectacular_websocket',
        'drf_spectacular',
        'drf_spectacular_sidecar',
    ]
    ```


## Configure settings
```python
ASGI_APPLICATION = 'path.to.your.application'

# (Optional) this is default settings are automatically set by the drf_spectacular_websocket.
# You can override them in your application if necessary.
SPECTACULAR_SETTINGS = {
    'DEFAULT_GENERATOR_CLASS': 'drf_spectacular_websocket.schemas.WsSchemaGenerator',
    'SWAGGER_UI_DIST': 'SIDECAR',
    'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
    'REDOC_DIST': 'SIDECAR',
    'SWAGGER_UI_SETTINGS': {
        'connectSocket': True,  # Automatically establish a WS connection when opening swagger
        'socketMaxMessages': 8,  # Max number of messages displayed in the log window in swagger
        'socketMessagesInitialOpened': False,  # Automatically open the log window when opening swagger
    },
}
```

> drf_spectacular_websocket automatically finds websocket urls and related consumer using `ASGI_APPLICATION` setting.

## About decorator
`extend_ws_schema` decorator accepts one new `type` parameter relative to drf_spectacular `extend_schema`.
- possible values:
    - `send` - Type of interaction, [request -> response]
    - `receive` - Type of interaction, [response without request]

## Usage example

```python
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from rest_framework.serializers import Serializer, CharField
from drf_spectacular_websocket.decorators import extend_ws_schema


class SomeMethodInputSerializer(Serializer):
    some_field = CharField()


class SomeMethodOutputSerializer(Serializer):
    some_field = CharField()


class SendMessageOutputSerializer(Serializer):
    some_field = CharField()


class SomeConsumer(AsyncJsonWebsocketConsumer):

    async def receive_json(self, content, **kwargs):
        some_value = content.get('some_key')
        if some_value:
            await self.some_method(some_value)

    @extend_ws_schema(
        type='send',
        summary='some_method_summary',
        description='some_method_description',
        request=SomeMethodInputSerializer,
        responses=SomeMethodOutputSerializer,
    )
    async def some_method(self, some_value):
        input_serializer = SomeMethodInputSerializer(data=some_value)
        input_serializer.is_valid(raise_exception=True)

        return_value = await some_business_logic(input_serializer.validated_data)

        output_serializer = SomeMethodOutputSerializer(data=return_value)
        output_serializer.is_valid(raise_exception=True)

        await self.send_json(output_serializer.validated_data)

    @extend_ws_schema(
        type='receive',
        summary='send_message_summary',
        description='send_message_description',
        request=None,
        responses=SendMessageOutputSerializer,
    )
    async def send_message(self, message):
        await self.send_json(message)
```

## Contributing
We would love you to contribute to `drf-spectacular-websocket`, pull requests are very welcome! Please see [CONTRIBUTING.md](https://github.com/Friskes/drf-spectacular-websocket/blob/main/CONTRIBUTING.md) for more information.

## Swagger Examples

### Send
![](https://raw.githubusercontent.com/Friskes/drf-spectacular-websocket/main/images/example_send.png)

### Receive
![](https://raw.githubusercontent.com/Friskes/drf-spectacular-websocket/main/images/example_receive.png)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Friskes/drf-spectacular-websocket",
    "name": "drf-spectacular-websocket",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "Django, DRF, Spectacular, Swagger, Channels",
    "author": "Friskes",
    "author_email": "Friskes <friskesx@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/6a/85/dc2bc00dc4422e48f2fe2307a9027865fc916256b7e0732dfe81e14f02dc/drf_spectacular_websocket-1.2.7.tar.gz",
    "platform": null,
    "description": "# Extend websocket schema decorator for Django Channels\n\n<div align=\"center\">\n\n| Project   |     | Status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |\n|-----------|:----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| CI/CD     |     | [![Latest Release](https://github.com/Friskes/drf-spectacular-websocket/actions/workflows/publish-to-pypi.yml/badge.svg)](https://github.com/Friskes/drf-spectacular-websocket/actions/workflows/publish-to-pypi.yml)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n| Quality   |     | [![Coverage](https://codecov.io/github/Friskes/drf-spectacular-websocket/graph/badge.svg?token=vKez4Pycrc)](https://codecov.io/github/Friskes/drf-spectacular-websocket)                                                                                                                                                                                                                                                                                                                               |\n| Package   |     | [![PyPI - Version](https://img.shields.io/pypi/v/drf-spectacular-websocket?labelColor=202235&color=edb641&logo=python&logoColor=edb641)](https://badge.fury.io/py/drf-spectacular-websocket) ![PyPI - Support Python Versions](https://img.shields.io/pypi/pyversions/drf-spectacular-websocket?labelColor=202235&color=edb641&logo=python&logoColor=edb641) ![Project PyPI - Downloads](https://img.shields.io/pypi/dm/drf-spectacular-websocket?logo=python&label=downloads&labelColor=202235&color=edb641&logoColor=edb641)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |\n| Meta      |     | [![types - Mypy](https://img.shields.io/badge/types-Mypy-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://github.com/python/mypy) [![License - MIT](https://img.shields.io/badge/license-MIT-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://spdx.org/licenses/) [![code style - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/format.json&labelColor=202235)](https://github.com/astral-sh/ruff) |\n\n</div>\n\n> Provides [extend_ws_schema](#About-decorator) decorator to documentation [Cunsumer](https://channels.readthedocs.io/en/latest/topics/consumers.html) methods from [channels](https://github.com/django/channels) just like it does [drf-spectacular](https://github.com/tfranzel/drf-spectacular)\n\n\n## Install\n1. Install package\n    ```bash\n    pip install drf-spectacular-websocket\n    ```\n\n2. Create sidecar static\n    ```bash\n    python manage.py collectstatic\n    ```\n\n3. Add app name to `INSTALLED_APPS`\n    > `drf_spectacular_websocket` must be higher than `drf_spectacular`\n    ```python\n    INSTALLED_APPS = [\n        'drf_spectacular_websocket',\n        'drf_spectacular',\n        'drf_spectacular_sidecar',\n    ]\n    ```\n\n\n## Configure settings\n```python\nASGI_APPLICATION = 'path.to.your.application'\n\n# (Optional) this is default settings are automatically set by the drf_spectacular_websocket.\n# You can override them in your application if necessary.\nSPECTACULAR_SETTINGS = {\n    'DEFAULT_GENERATOR_CLASS': 'drf_spectacular_websocket.schemas.WsSchemaGenerator',\n    'SWAGGER_UI_DIST': 'SIDECAR',\n    'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',\n    'REDOC_DIST': 'SIDECAR',\n    'SWAGGER_UI_SETTINGS': {\n        'connectSocket': True,  # Automatically establish a WS connection when opening swagger\n        'socketMaxMessages': 8,  # Max number of messages displayed in the log window in swagger\n        'socketMessagesInitialOpened': False,  # Automatically open the log window when opening swagger\n    },\n}\n```\n\n> drf_spectacular_websocket automatically finds websocket urls and related consumer using `ASGI_APPLICATION` setting.\n\n## About decorator\n`extend_ws_schema` decorator accepts one new `type` parameter relative to drf_spectacular `extend_schema`.\n- possible values:\n    - `send` - Type of interaction, [request -> response]\n    - `receive` - Type of interaction, [response without request]\n\n## Usage example\n\n```python\nfrom channels.generic.websocket import AsyncJsonWebsocketConsumer\nfrom rest_framework.serializers import Serializer, CharField\nfrom drf_spectacular_websocket.decorators import extend_ws_schema\n\n\nclass SomeMethodInputSerializer(Serializer):\n    some_field = CharField()\n\n\nclass SomeMethodOutputSerializer(Serializer):\n    some_field = CharField()\n\n\nclass SendMessageOutputSerializer(Serializer):\n    some_field = CharField()\n\n\nclass SomeConsumer(AsyncJsonWebsocketConsumer):\n\n    async def receive_json(self, content, **kwargs):\n        some_value = content.get('some_key')\n        if some_value:\n            await self.some_method(some_value)\n\n    @extend_ws_schema(\n        type='send',\n        summary='some_method_summary',\n        description='some_method_description',\n        request=SomeMethodInputSerializer,\n        responses=SomeMethodOutputSerializer,\n    )\n    async def some_method(self, some_value):\n        input_serializer = SomeMethodInputSerializer(data=some_value)\n        input_serializer.is_valid(raise_exception=True)\n\n        return_value = await some_business_logic(input_serializer.validated_data)\n\n        output_serializer = SomeMethodOutputSerializer(data=return_value)\n        output_serializer.is_valid(raise_exception=True)\n\n        await self.send_json(output_serializer.validated_data)\n\n    @extend_ws_schema(\n        type='receive',\n        summary='send_message_summary',\n        description='send_message_description',\n        request=None,\n        responses=SendMessageOutputSerializer,\n    )\n    async def send_message(self, message):\n        await self.send_json(message)\n```\n\n## Contributing\nWe would love you to contribute to `drf-spectacular-websocket`, pull requests are very welcome! Please see [CONTRIBUTING.md](https://github.com/Friskes/drf-spectacular-websocket/blob/main/CONTRIBUTING.md) for more information.\n\n## Swagger Examples\n\n### Send\n![](https://raw.githubusercontent.com/Friskes/drf-spectacular-websocket/main/images/example_send.png)\n\n### Receive\n![](https://raw.githubusercontent.com/Friskes/drf-spectacular-websocket/main/images/example_receive.png)\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Friskes  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:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  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. ",
    "summary": "Extend websocket schema decorator for Django Channels",
    "version": "1.2.7",
    "project_urls": {
        "Changelog": "https://github.com/Friskes/drf-spectacular-websocket/releases/",
        "Homepage": "https://github.com/Friskes/drf-spectacular-websocket",
        "Issues": "https://github.com/Friskes/drf-spectacular-websocket/issues"
    },
    "split_keywords": [
        "django",
        " drf",
        " spectacular",
        " swagger",
        " channels"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a6f4e0d11e9c386439001bdfed0517b2311a4e0b6a75e256f2306e4b2fbe1429",
                "md5": "e17f1318a0878f1c9ae0c07ff931a270",
                "sha256": "b9ccf83523a6443c9b05b2ac5e0862d2e644c1eb3265cfc92230e45564cb9cbd"
            },
            "downloads": -1,
            "filename": "drf_spectacular_websocket-1.2.7-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e17f1318a0878f1c9ae0c07ff931a270",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 16676,
            "upload_time": "2024-05-02T17:18:46",
            "upload_time_iso_8601": "2024-05-02T17:18:46.609778Z",
            "url": "https://files.pythonhosted.org/packages/a6/f4/e0d11e9c386439001bdfed0517b2311a4e0b6a75e256f2306e4b2fbe1429/drf_spectacular_websocket-1.2.7-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6a85dc2bc00dc4422e48f2fe2307a9027865fc916256b7e0732dfe81e14f02dc",
                "md5": "4dc593b4279fed45ce2dfbea9dd69d40",
                "sha256": "ee95b08b7696071a18ae491c802f7fdebd976d7b8247e1c08dfc3872b64b464c"
            },
            "downloads": -1,
            "filename": "drf_spectacular_websocket-1.2.7.tar.gz",
            "has_sig": false,
            "md5_digest": "4dc593b4279fed45ce2dfbea9dd69d40",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 162560,
            "upload_time": "2024-05-02T17:18:47",
            "upload_time_iso_8601": "2024-05-02T17:18:47.935677Z",
            "url": "https://files.pythonhosted.org/packages/6a/85/dc2bc00dc4422e48f2fe2307a9027865fc916256b7e0732dfe81e14f02dc/drf_spectacular_websocket-1.2.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-02 17:18:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Friskes",
    "github_project": "drf-spectacular-websocket",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "drf-spectacular-websocket"
}
        
Elapsed time: 0.24975s