django-nats-client


Namedjango-nats-client JSON
Version 0.4.3 PyPI version JSON
download
home_pagehttps://github.com/C0D1UM/django-nats-client
Summary
upload_time2024-02-17 11:09:53
maintainer
docs_urlNone
authorCODIUM
requires_python>=3.8,<4.0
licenseMIT
keywords django nats listener python
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # Django NATS Client

[![GitHub](https://img.shields.io/github/license/C0D1UM/django-nats-client)](https://github.com/C0D1UM/django-nats-client/blob/main/LICENSE)
[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/C0D1UM/django-nats-client/ci.yml?branch=main)](https://github.com/C0D1UM/django-nats-client/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/C0D1UM/django-nats-client/branch/main/graph/badge.svg?token=PN19DJ3SDF)](https://codecov.io/gh/C0D1UM/django-nats-client)
[![PyPI](https://img.shields.io/pypi/v/django-nats-client)](https://pypi.org/project/django-nats-client/)  
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-nats-client)](https://github.com/C0D1UM/django-nats-client)

## Important Notes

> 🚨 The latest major version of this package, `v0.4.0`, has a numerous breaking changes.
> Please review its [release note](https://github.com/C0D1UM/django-nats-client/releases/tag/v0.4.0).

## Features

- Wrapper of NATS's [nats-py](https://github.com/nats-io/nats.py)
- Django management command to listen for incoming NATS messages
- Automatically serialize/deserialize message from/to JSON format
- Easy-to-call method for publishing NATS messages
- Support NATS JetStream pull subscription

## Installation

```bash
pip install django-nats-client
```

## Setup

1. Add `nats_client` into `INSTALLED_APPS`

   ```python
   # settings.py

   INSTALLED_APPS = [
       ...
       'nats_client',
   ]
   ```

1. Put NATS connection configuration in settings

   ```python
   # settings.py

   NATS_SERVERS = 'nats://localhost:4222'
   NATS_NAMESPACE = 'foo'
   ```

## Usage

### Listen for messages

1. Create a new callback method and register

   ```python
   # common/nats.py

   import nats_client
   
   @nats_client.register
   def new_message(message: str):
       print(message)

   @nats_client.register
   def get_year_from_date(date: str):
       return date.year

   # custom name
   @nats_client.register('get_current_time')
   def current_time():
       return datetime.datetime.now().strftime('%H:%M')

   # without decorator
   def current_time():
       return datetime.datetime.now().strftime('%H:%M')
   nats_client.register('get_current_time', current_time)
   
   # JetStream
   @nats_client.register(js=True)
   def new_message(message: str):
       print(message)
   
   # JetStream from other namespace
   @nats_client.register(namespace='bar', js=True)
   def new_message_from_bar(message: str):
       print(message)
   ```

1. Import previously file in `ready` method of your `apps.py`

   ```python
   # common/apps.py

   class CommonConfig(AppConfig):
       ...

       def ready(self):
           import common.nats
   ```

1. Run listener management command

   ```bash
   python manage.py nats_listener

   # or with autoreload enabled (suite for development)
   python manage.py nats_listener --reload
   ```

### Publishing message

```python
import nats_client

arg = 'some arg'
await nats_client.publish(
    'subject_name',
    'method_name',
    arg,
    keyword_arg=1,
    another_keyword_arg=2,
)
```

Examples

```python
import nats_client

await nats_client.publish('default', 'new_message', 'Hello, world!')
await nats_client.publish('default', 'project_created', 1, name='ACME')

# JetStream
await nats_client.publish('default', 'new_message', 'Hello, world!', _js=True)
await nats_client.js_publish('default', 'new_message', 'Hello, world!')
```

### Request-Reply

```python
import nats_client

arg = 'some arg'
await nats_client.request(
    'subject_name',
    'method_name',
    arg,
    keyword_arg=1,
    another_keyword_arg=2,
)
```

Examples

```python
import nats_client

year = await nats_client.request('default', 'get_year_from_date', datetime.date(2022, 1, 1))  # 2022
current_time = await nats_client.request('default', 'get_current_time')  # 12:11
```

## Settings

| Key                            | Type        | Required                      | Default                   | Description                                                       |
|--------------------------------|-------------|-------------------------------|---------------------------|-------------------------------------------------------------------|
| `NATS_SERVER`                  | `str`       | Required if no `NATS_SERVERS` |                           | NATS server's host                                                |
| `NATS_SERVERS`                 | `list[str]` | Required if no `NATS_SERVER`  |                           | NATS server's hosts (for NATS cluster)                            |
| `NATS_NAMESPACE`               | `str`       | No                            | `'default'`               | Main namespace using for prefixing subject, stream name, and etc. |
| `NATS_REQUEST_TIMEOUT`         | `int`       | No                            | `1`                       | Timeout when using `request()` (in seconds)                       |
| `NATS_OPTIONS`                 | `dict`      | No                            | `{}`                      | Other configuration to be passed in `nats.connect()`              |
| `NATS_JETSTREAM_ENABLED`       | `bool`      | No                            | `True`                    | Enable JetStream                                                  |
| `NATS_JETSTREAM_DURABLE_NAME`  | `str`       | No                            | `settings.NATS_NAMESPACE` | Durable name which is unique across all subscriptions             |
| `NATS_JETSTREAM_CREATE_STREAM` | `bool`      | No                            | `True`                    | Automatically create stream named in `NATS_NAMESPACE`             |
| `NATS_JETSTREAM_CONFIG`        | `dict`      | No                            | `{}`                      | Extra configuration for JetStream streams                         |

## Development

### Requirements

- Docker
- Python
- Poetry

### Linting

```bash
make lint
```

### Testing

```bash
make test
```

### Fix Formatting

```bash
make yapf
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/C0D1UM/django-nats-client",
    "name": "django-nats-client",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "django,nats,listener,python",
    "author": "CODIUM",
    "author_email": "support@codium.co",
    "download_url": "https://files.pythonhosted.org/packages/2e/bc/de74ac71197b254e133ceb8dceec521da6c62112ad2b17b8490d3cec9ad3/django_nats_client-0.4.3.tar.gz",
    "platform": null,
    "description": "# Django NATS Client\n\n[![GitHub](https://img.shields.io/github/license/C0D1UM/django-nats-client)](https://github.com/C0D1UM/django-nats-client/blob/main/LICENSE)\n[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/C0D1UM/django-nats-client/ci.yml?branch=main)](https://github.com/C0D1UM/django-nats-client/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/C0D1UM/django-nats-client/branch/main/graph/badge.svg?token=PN19DJ3SDF)](https://codecov.io/gh/C0D1UM/django-nats-client)\n[![PyPI](https://img.shields.io/pypi/v/django-nats-client)](https://pypi.org/project/django-nats-client/)  \n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-nats-client)](https://github.com/C0D1UM/django-nats-client)\n\n## Important Notes\n\n> \ud83d\udea8 The latest major version of this package, `v0.4.0`, has a numerous breaking changes.\n> Please review its [release note](https://github.com/C0D1UM/django-nats-client/releases/tag/v0.4.0).\n\n## Features\n\n- Wrapper of NATS's [nats-py](https://github.com/nats-io/nats.py)\n- Django management command to listen for incoming NATS messages\n- Automatically serialize/deserialize message from/to JSON format\n- Easy-to-call method for publishing NATS messages\n- Support NATS JetStream pull subscription\n\n## Installation\n\n```bash\npip install django-nats-client\n```\n\n## Setup\n\n1. Add `nats_client` into `INSTALLED_APPS`\n\n   ```python\n   # settings.py\n\n   INSTALLED_APPS = [\n       ...\n       'nats_client',\n   ]\n   ```\n\n1. Put NATS connection configuration in settings\n\n   ```python\n   # settings.py\n\n   NATS_SERVERS = 'nats://localhost:4222'\n   NATS_NAMESPACE = 'foo'\n   ```\n\n## Usage\n\n### Listen for messages\n\n1. Create a new callback method and register\n\n   ```python\n   # common/nats.py\n\n   import nats_client\n   \n   @nats_client.register\n   def new_message(message: str):\n       print(message)\n\n   @nats_client.register\n   def get_year_from_date(date: str):\n       return date.year\n\n   # custom name\n   @nats_client.register('get_current_time')\n   def current_time():\n       return datetime.datetime.now().strftime('%H:%M')\n\n   # without decorator\n   def current_time():\n       return datetime.datetime.now().strftime('%H:%M')\n   nats_client.register('get_current_time', current_time)\n   \n   # JetStream\n   @nats_client.register(js=True)\n   def new_message(message: str):\n       print(message)\n   \n   # JetStream from other namespace\n   @nats_client.register(namespace='bar', js=True)\n   def new_message_from_bar(message: str):\n       print(message)\n   ```\n\n1. Import previously file in `ready` method of your `apps.py`\n\n   ```python\n   # common/apps.py\n\n   class CommonConfig(AppConfig):\n       ...\n\n       def ready(self):\n           import common.nats\n   ```\n\n1. Run listener management command\n\n   ```bash\n   python manage.py nats_listener\n\n   # or with autoreload enabled (suite for development)\n   python manage.py nats_listener --reload\n   ```\n\n### Publishing message\n\n```python\nimport nats_client\n\narg = 'some arg'\nawait nats_client.publish(\n    'subject_name',\n    'method_name',\n    arg,\n    keyword_arg=1,\n    another_keyword_arg=2,\n)\n```\n\nExamples\n\n```python\nimport nats_client\n\nawait nats_client.publish('default', 'new_message', 'Hello, world!')\nawait nats_client.publish('default', 'project_created', 1, name='ACME')\n\n# JetStream\nawait nats_client.publish('default', 'new_message', 'Hello, world!', _js=True)\nawait nats_client.js_publish('default', 'new_message', 'Hello, world!')\n```\n\n### Request-Reply\n\n```python\nimport nats_client\n\narg = 'some arg'\nawait nats_client.request(\n    'subject_name',\n    'method_name',\n    arg,\n    keyword_arg=1,\n    another_keyword_arg=2,\n)\n```\n\nExamples\n\n```python\nimport nats_client\n\nyear = await nats_client.request('default', 'get_year_from_date', datetime.date(2022, 1, 1))  # 2022\ncurrent_time = await nats_client.request('default', 'get_current_time')  # 12:11\n```\n\n## Settings\n\n| Key                            | Type        | Required                      | Default                   | Description                                                       |\n|--------------------------------|-------------|-------------------------------|---------------------------|-------------------------------------------------------------------|\n| `NATS_SERVER`                  | `str`       | Required if no `NATS_SERVERS` |                           | NATS server's host                                                |\n| `NATS_SERVERS`                 | `list[str]` | Required if no `NATS_SERVER`  |                           | NATS server's hosts (for NATS cluster)                            |\n| `NATS_NAMESPACE`               | `str`       | No                            | `'default'`               | Main namespace using for prefixing subject, stream name, and etc. |\n| `NATS_REQUEST_TIMEOUT`         | `int`       | No                            | `1`                       | Timeout when using `request()` (in seconds)                       |\n| `NATS_OPTIONS`                 | `dict`      | No                            | `{}`                      | Other configuration to be passed in `nats.connect()`              |\n| `NATS_JETSTREAM_ENABLED`       | `bool`      | No                            | `True`                    | Enable JetStream                                                  |\n| `NATS_JETSTREAM_DURABLE_NAME`  | `str`       | No                            | `settings.NATS_NAMESPACE` | Durable name which is unique across all subscriptions             |\n| `NATS_JETSTREAM_CREATE_STREAM` | `bool`      | No                            | `True`                    | Automatically create stream named in `NATS_NAMESPACE`             |\n| `NATS_JETSTREAM_CONFIG`        | `dict`      | No                            | `{}`                      | Extra configuration for JetStream streams                         |\n\n## Development\n\n### Requirements\n\n- Docker\n- Python\n- Poetry\n\n### Linting\n\n```bash\nmake lint\n```\n\n### Testing\n\n```bash\nmake test\n```\n\n### Fix Formatting\n\n```bash\nmake yapf\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "",
    "version": "0.4.3",
    "project_urls": {
        "Homepage": "https://github.com/C0D1UM/django-nats-client",
        "Repository": "https://github.com/C0D1UM/django-nats-client"
    },
    "split_keywords": [
        "django",
        "nats",
        "listener",
        "python"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a768e86f0bf250906943451704f6dc28445791a0c366b896562c4c62b23e3fcd",
                "md5": "0e637a20b000c3ad782b467df86494c2",
                "sha256": "b6a0e63bcf44b8bd7fcdb44256d20bcb6e9236bb87d21d923f9c63b0dbaad6dc"
            },
            "downloads": -1,
            "filename": "django_nats_client-0.4.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0e637a20b000c3ad782b467df86494c2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 9212,
            "upload_time": "2024-02-17T11:09:50",
            "upload_time_iso_8601": "2024-02-17T11:09:50.416395Z",
            "url": "https://files.pythonhosted.org/packages/a7/68/e86f0bf250906943451704f6dc28445791a0c366b896562c4c62b23e3fcd/django_nats_client-0.4.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2ebcde74ac71197b254e133ceb8dceec521da6c62112ad2b17b8490d3cec9ad3",
                "md5": "ef44e2f41439ce5bf47df35e01e2d9a0",
                "sha256": "86b4301b1a5e50197ef6ec97fba7e0ac6d91916a5856497d2faa08854d757b3e"
            },
            "downloads": -1,
            "filename": "django_nats_client-0.4.3.tar.gz",
            "has_sig": false,
            "md5_digest": "ef44e2f41439ce5bf47df35e01e2d9a0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 8507,
            "upload_time": "2024-02-17T11:09:53",
            "upload_time_iso_8601": "2024-02-17T11:09:53.301564Z",
            "url": "https://files.pythonhosted.org/packages/2e/bc/de74ac71197b254e133ceb8dceec521da6c62112ad2b17b8490d3cec9ad3/django_nats_client-0.4.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-17 11:09:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "C0D1UM",
    "github_project": "django-nats-client",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "django-nats-client"
}
        
Elapsed time: 0.26048s