django-instant


Namedjango-instant JSON
Version 4.2.0 PyPI version JSON
download
home_pagehttps://github.com/synw/django-instant
SummaryWebsockets for Django with Centrifugo
upload_time2022-12-19 11:04:26
maintainer
docs_urlNone
authorsynw
requires_python
license
keywords django websockets centrifugo
VCS
bugtrack_url
requirements cent PyJWT
Travis-CI
coveralls test coverage No coveralls.
            # Django Instant

[![pub package](https://img.shields.io/pypi/v/django-instant)](https://pypi.org/project/django-instant/) [![Django CI](https://github.com/synw/django-instant/actions/workflows/django.yml/badge.svg)](https://github.com/synw/django-instant/actions/workflows/django.yml)

Websockets for Django with [Centrifugo](https://github.com/centrifugal/centrifugo).

* Push events into public or private channels.
* Handle the events in javascript client-side.

:sunny: Compatible: plug it on an existing Django instance _without any modification in your main stack_

### Example

Push events in channels from anywhere in the code:

  ```python
from instant.producers import publish
  
# Publish to a public channel
publish("public", "Message for everyone")

# Publish to a private channel with an event class set
publish("$users", "Message in logged in users channel", event_class="important")

# Publish to a group channel
publish("$group1", "Message for users in group1")

# Publish to the staff channel with an extra json data payload
data = {"field1":"value1","field2":[1,2]}
publish("$staff", "Message for staff", data=data)
  ```

## Quick start

### Install the Django package

```
pip install django-instant
```

Add `"instant"` to `INSTALLED_APPS` and update `urls.py`:

```python
urlpatterns = [
    # ...
    path("instant/", include("instant.urls")),
]
```

### Install the websockets server

#### Using the installer

Use the Centrifugo installer management command (for Linux and MacOs):

```
python manage.py installws
```

This will download a Centrifugo binary release and install it under a *centrifugo* directory. It will
generate the Django settings to use.

#### Install manualy

Install the Centrifugo websockets server: see the [detailled doc](https://centrifugal.github.io/centrifugo/server/install/) 
 
<details>
<br />
Download a release https://github.com/centrifugal/centrifugo/releases/latest
and generate a configuration file:

```
./centrifugo genconfig
```

The generated `config.json` file looks like this:

```javascript
{
  "v3_use_offset": true,
  "token_hmac_secret_key": "46b38493-147e-4e3f-86e0-dc5ec54f5133",
  "admin_password": "ad0dff75-3131-4a02-8d64-9279b4f1c57b",
  "admin_secret": "583bc4b7-0fa5-4c4a-8566-16d3ce4ad401",
  "api_key": "aaaf202f-b5f8-4b34-bf88-f6c03a1ecda6",
  "allowed_origins": []
}
```
</details>

### Configure the Django settings

Use the parameters from the installer's output or from Centrifugo's `config.json` file 
to update your Django's `settings.py`:

```python
CENTRIFUGO_HOST = "http://localhost"
CENTRIFUGO_PORT = 8001
CENTRIFUGO_HMAC_KEY = "46b38493-147e-4e3f-86e0-dc5ec54f5133"
CENTRIFUGO_API_KEY = "aaaf202f-b5f8-4b34-bf88-f6c03a1ecda6"
SITE_NAME = "My site" # used in the messages to identify where they come from
```

### Create channels

Go into the admin to create channels or create them programatically:

```python
from instant.models import Channel

Channel.objects.create(name="superuser", level=Channel.Level.Superuser) 
```

Api: channel create parameters:

- `name`: the channel name. Required and unique
- `level`: access authorization level for a channel: *Public, Users, Groups, Staff, Superuser*. Default: *Superuser*
- `is_active`: a boolean to disable a channel
- `groups`: a list of authorized Django groups for a channel

## Avalailable endpoints

`/instant/login/`: takes a username and password as parameter and will login the
user in Django and return a Centrifugo connection token

`/instant/get_token/`: get a Centrifugo connection token for a logged in user

The two methods above return some connection information: a token for
the websockets connection, a Django csrf token and a list of authorized
channels for the user:

```javascript
{
  "csrf_token": "fvO61oyhcfzrW3SjPCYxYfzDAQFO6Yz7yaAQkxDbhC0NhlwoP1cecqLEYv8SCDLK",
  "ws_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZ2ciLCJleHAiOjE2M..",
  "channels": [
    {
      "name": "public",
      "level": "public"
    },
    {
      "name": "$users",
      "level": "users"
    },
    {
      "name": "$group1",
      "level": "groups"
    }
  ]
}
```

`/instant/subscribe/`: get tokens for Centrifugo channels subscriptions 
([doc](https://centrifugal.github.io/centrifugo/server/private_channels/))

## Publish method

The required parameters are `channel` and either `message` or `data`

```python
publish("$users", "A message", data={
        "foo": "bar"}, event_class="important", bucket="notifications")
```

The other parameters are optional

## Javascript client

Several options are available for the client side

### Use the official Centrifugo js client

Manage your websockets connection manually with the official Centrifugo js library: 
[Centrifuge-js](https://github.com/centrifugal/centrifuge-js)

### Use the embeded client in a script tag

In a Django template:

```html
{% load static %}
<script src="{% static 'instant/index.min.js' %}"></script>
<script>
  const instant = $instant.useInstant();
</script>
```

[Api doc](https://github.com/synw/djangoinstant#usage)

### Use the npm client

A dedicated [client](https://github.com/synw/djangoinstant) is available from npm
to handle the messages and connections client side in javascript or typescript

## Example

An [example](https://github.com/synw/django-instant-example) with a backend and a frontend is available

## Tests

To run the tests:

```bash
tox
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/synw/django-instant",
    "name": "django-instant",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "django,websockets,centrifugo",
    "author": "synw",
    "author_email": "synwe@yahoo.com",
    "download_url": "https://files.pythonhosted.org/packages/a6/da/86eada6230c24226d8d2f39e964c29c68cef5c618aaf64910fcfd7ddce24/django-instant-4.2.0.tar.gz",
    "platform": null,
    "description": "# Django Instant\n\n[![pub package](https://img.shields.io/pypi/v/django-instant)](https://pypi.org/project/django-instant/) [![Django CI](https://github.com/synw/django-instant/actions/workflows/django.yml/badge.svg)](https://github.com/synw/django-instant/actions/workflows/django.yml)\n\nWebsockets for Django with [Centrifugo](https://github.com/centrifugal/centrifugo).\n\n* Push events into public or private channels.\n* Handle the events in javascript client-side.\n\n:sunny: Compatible: plug it on an existing Django instance _without any modification in your main stack_\n\n### Example\n\nPush events in channels from anywhere in the code:\n\n  ```python\nfrom instant.producers import publish\n  \n# Publish to a public channel\npublish(\"public\", \"Message for everyone\")\n\n# Publish to a private channel with an event class set\npublish(\"$users\", \"Message in logged in users channel\", event_class=\"important\")\n\n# Publish to a group channel\npublish(\"$group1\", \"Message for users in group1\")\n\n# Publish to the staff channel with an extra json data payload\ndata = {\"field1\":\"value1\",\"field2\":[1,2]}\npublish(\"$staff\", \"Message for staff\", data=data)\n  ```\n\n## Quick start\n\n### Install the Django package\n\n```\npip install django-instant\n```\n\nAdd `\"instant\"` to `INSTALLED_APPS` and update `urls.py`:\n\n```python\nurlpatterns = [\n    # ...\n    path(\"instant/\", include(\"instant.urls\")),\n]\n```\n\n### Install the websockets server\n\n#### Using the installer\n\nUse the Centrifugo installer management command (for Linux and MacOs):\n\n```\npython manage.py installws\n```\n\nThis will download a Centrifugo binary release and install it under a *centrifugo* directory. It will\ngenerate the Django settings to use.\n\n#### Install manualy\n\nInstall the Centrifugo websockets server: see the [detailled doc](https://centrifugal.github.io/centrifugo/server/install/) \n \n<details>\n<br />\nDownload a release https://github.com/centrifugal/centrifugo/releases/latest\nand generate a configuration file:\n\n```\n./centrifugo genconfig\n```\n\nThe generated `config.json` file looks like this:\n\n```javascript\n{\n  \"v3_use_offset\": true,\n  \"token_hmac_secret_key\": \"46b38493-147e-4e3f-86e0-dc5ec54f5133\",\n  \"admin_password\": \"ad0dff75-3131-4a02-8d64-9279b4f1c57b\",\n  \"admin_secret\": \"583bc4b7-0fa5-4c4a-8566-16d3ce4ad401\",\n  \"api_key\": \"aaaf202f-b5f8-4b34-bf88-f6c03a1ecda6\",\n  \"allowed_origins\": []\n}\n```\n</details>\n\n### Configure the Django settings\n\nUse the parameters from the installer's output or from Centrifugo's `config.json` file \nto update your Django's `settings.py`:\n\n```python\nCENTRIFUGO_HOST = \"http://localhost\"\nCENTRIFUGO_PORT = 8001\nCENTRIFUGO_HMAC_KEY = \"46b38493-147e-4e3f-86e0-dc5ec54f5133\"\nCENTRIFUGO_API_KEY = \"aaaf202f-b5f8-4b34-bf88-f6c03a1ecda6\"\nSITE_NAME = \"My site\" # used in the messages to identify where they come from\n```\n\n### Create channels\n\nGo into the admin to create channels or create them programatically:\n\n```python\nfrom instant.models import Channel\n\nChannel.objects.create(name=\"superuser\", level=Channel.Level.Superuser) \n```\n\nApi: channel create parameters:\n\n- `name`: the channel name. Required and unique\n- `level`: access authorization level for a channel: *Public, Users, Groups, Staff, Superuser*. Default: *Superuser*\n- `is_active`: a boolean to disable a channel\n- `groups`: a list of authorized Django groups for a channel\n\n## Avalailable endpoints\n\n`/instant/login/`: takes a username and password as parameter and will login the\nuser in Django and return a Centrifugo connection token\n\n`/instant/get_token/`: get a Centrifugo connection token for a logged in user\n\nThe two methods above return some connection information: a token for\nthe websockets connection, a Django csrf token and a list of authorized\nchannels for the user:\n\n```javascript\n{\n  \"csrf_token\": \"fvO61oyhcfzrW3SjPCYxYfzDAQFO6Yz7yaAQkxDbhC0NhlwoP1cecqLEYv8SCDLK\",\n  \"ws_token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZ2ciLCJleHAiOjE2M..\",\n  \"channels\": [\n    {\n      \"name\": \"public\",\n      \"level\": \"public\"\n    },\n    {\n      \"name\": \"$users\",\n      \"level\": \"users\"\n    },\n    {\n      \"name\": \"$group1\",\n      \"level\": \"groups\"\n    }\n  ]\n}\n```\n\n`/instant/subscribe/`: get tokens for Centrifugo channels subscriptions \n([doc](https://centrifugal.github.io/centrifugo/server/private_channels/))\n\n## Publish method\n\nThe required parameters are `channel` and either `message` or `data`\n\n```python\npublish(\"$users\", \"A message\", data={\n        \"foo\": \"bar\"}, event_class=\"important\", bucket=\"notifications\")\n```\n\nThe other parameters are optional\n\n## Javascript client\n\nSeveral options are available for the client side\n\n### Use the official Centrifugo js client\n\nManage your websockets connection manually with the official Centrifugo js library: \n[Centrifuge-js](https://github.com/centrifugal/centrifuge-js)\n\n### Use the embeded client in a script tag\n\nIn a Django template:\n\n```html\n{% load static %}\n<script src=\"{% static 'instant/index.min.js' %}\"></script>\n<script>\n  const instant = $instant.useInstant();\n</script>\n```\n\n[Api doc](https://github.com/synw/djangoinstant#usage)\n\n### Use the npm client\n\nA dedicated [client](https://github.com/synw/djangoinstant) is available from npm\nto handle the messages and connections client side in javascript or typescript\n\n## Example\n\nAn [example](https://github.com/synw/django-instant-example) with a backend and a frontend is available\n\n## Tests\n\nTo run the tests:\n\n```bash\ntox\n```\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Websockets for Django with Centrifugo",
    "version": "4.2.0",
    "split_keywords": [
        "django",
        "websockets",
        "centrifugo"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "578df69831d122e37f1df55ba7f2c585",
                "sha256": "bf4288480a042639ec7f71ded209a47c7e029ea2eb5723e3669632b7098977ae"
            },
            "downloads": -1,
            "filename": "django_instant-4.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "578df69831d122e37f1df55ba7f2c585",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 34193,
            "upload_time": "2022-12-19T11:04:24",
            "upload_time_iso_8601": "2022-12-19T11:04:24.468895Z",
            "url": "https://files.pythonhosted.org/packages/41/cf/209fc30cf4e8c11e05dfb1c80a95839aaedc2df7cc910ebeb85080d75f75/django_instant-4.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "dc14904f28e61cc23505ce8f99f125dc",
                "sha256": "355693c6a27b8e906fa34bb3490b3269a465401229f8f737258577f500b125d6"
            },
            "downloads": -1,
            "filename": "django-instant-4.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "dc14904f28e61cc23505ce8f99f125dc",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 27853,
            "upload_time": "2022-12-19T11:04:26",
            "upload_time_iso_8601": "2022-12-19T11:04:26.618026Z",
            "url": "https://files.pythonhosted.org/packages/a6/da/86eada6230c24226d8d2f39e964c29c68cef5c618aaf64910fcfd7ddce24/django-instant-4.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-12-19 11:04:26",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "synw",
    "github_project": "django-instant",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "cent",
            "specs": []
        },
        {
            "name": "PyJWT",
            "specs": []
        }
    ],
    "tox": true,
    "lcname": "django-instant"
}
        
Elapsed time: 0.01870s