{"id":22923998,"url":"https://github.com/tobi-de/sse_relay_server","last_synced_at":"2025-06-29T00:33:05.747Z","repository":{"id":194958144,"uuid":"691791640","full_name":"Tobi-De/sse_relay_server","owner":"Tobi-De","description":"An SSE Relay Service: Perfect for Adding Real-Time Features to Your Django Project Without Introducing ASGI or Async Code.","archived":false,"fork":false,"pushed_at":"2024-03-20T08:35:33.000Z","size":607,"stargazers_count":18,"open_issues_count":2,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-13T11:11:21.318Z","etag":null,"topics":["django","postgresql","python3","realtime","redis","relay","sse"],"latest_commit_sha":null,"homepage":"https://github.com/Tobi-De/sse_relay_server","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Tobi-De.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-09-14T22:44:17.000Z","updated_at":"2025-01-01T08:52:04.000Z","dependencies_parsed_at":"2023-09-15T23:56:33.591Z","dependency_job_id":"7a7c6e16-fb42-4d0b-9ea7-2379e2b6ad11","html_url":"https://github.com/Tobi-De/sse_relay_server","commit_stats":null,"previous_names":["tobi-de/sse_relay_server"],"tags_count":12,"template":false,"template_full_name":null,"purl":"pkg:github/Tobi-De/sse_relay_server","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tobi-De%2Fsse_relay_server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tobi-De%2Fsse_relay_server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tobi-De%2Fsse_relay_server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tobi-De%2Fsse_relay_server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Tobi-De","download_url":"https://codeload.github.com/Tobi-De/sse_relay_server/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tobi-De%2Fsse_relay_server/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262518102,"owners_count":23323301,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","postgresql","python3","realtime","redis","relay","sse"],"created_at":"2024-12-14T08:18:59.833Z","updated_at":"2025-06-29T00:33:05.707Z","avatar_url":"https://github.com/Tobi-De.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# sse-relay-server\n\n[![Docker](https://github.com/Tobi-De/sse_relay_server/actions/workflows/docker-publish.yml/badge.svg)](https://github.com/Tobi-De/sse_relay_server/actions/workflows/docker-publish.yml)\n[![pypi](https://badge.fury.io/py/sse-relay-server.svg)](https://pypi.org/project/sse-relay-server/)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/Tobi-De/fuzzy-couscous/blob/main/LICENSE)\n[![GitHub Container Registry](https://img.shields.io/badge/Docker%20Pulls-GitHub%20Container%20Registry-blue)](https://github.com/Tobi-De/sse_relay_server/pkgs/container/sse_relay_server)\n\nFor some background information, read https://github.com/Tobi-De/sse_server_postgres_listen_notify.\n\nOriginally designed for Django, now a simple, standalone Server-Sent Events relay service, ideal for Django projects\nseeking\nstraightforward real-time capabilities without the need for Daphne and async Django setup.\n\n![SSE relay message transmission diagram](diagram.png)\n\n\u003cdetails\u003e\n\u003csummary\u003eExplanation\u003c/summary\u003e\n\n1. The browser establishes an SSE connection to the running relay service (this project).\n2. The relay service listens on the channel specified in the user request via the path parameter `channel`.\n3. When a user action occurs on your Django server, you run the [`notify`](#sending-messages-from-your-django-app) function, sending an event to either `PostgreSQL` or `Redis` based on your configuration.\n4. The relay service receives the message from the broker (`Redis`/`PostgreSQL`).\n5. Subsequently, the relay sends the message via SSE to all web browsers subscribed to the specified channel.\n\n\u003c/details\u003e\n\n## Installation\n\nYou can install sse-relay-server as a package using pip:\n\n```sh\npip install \"sse-relay-server[postgres,redis]\"\n```\n\nAlternatively, you can use a container by pulling the Docker image:\n\n```sh\ndocker pull ghcr.io/tobi-de/sse_relay_server:latest\n```\n\n## Supported Protocols\n\n- PostgreSQL [LISTEN](https://www.postgresql.org/docs/current/sql-listen.html)/[NOTIFY](https://www.postgresql.org/docs/15/sql-notify.html)\n- Redis [Pub/Sub](https://redis.io/topics/pubsub)\n\n## Environment Variables\n\nTo configure sse-relay-server, you can use the following environment variables:\n\n- `ALLOWED_ORIGINS`: Comma-separated URLs allowed to request SSE connections.\n- `DATABASE_URL`: PostgreSQL database URL.\n- `REDIS_URL`: Redis URL (if you prefer to use Redis instead of PostgreSQL).\n- `RELAY_USE_PG`: Force the use of PostgreSQL if you have both `REDIS_URL` and `DATABASE_URL` set, but prefer to use PostgreSQL.\n- `RELAY_SERVER_DEBUG`: Boolean for enabling debug mode (default to False).\n- `LOG_LEVEL`: CRITICAL | ERROR | WARNING | INFO | DEBUG | TRACE   (default to INFO)\n\nIf the `REDIS_URL` environment variable is set, the redis pubsub protocol will be used instead of the PostgreSQL\nlisten/notify.\n\n## Running the Relay Service\n\nIf installed via pip, simply execute the following command, adjusting the options as needed:\n\n```sh\nsse-relay-server --port 8001 --host 0.0.0.0 --workers 4\n```\n\nFor Docker users, override the running command as follows:\n\n```sh\ndocker run -it sse_relay_server sse-relay-server --port 8001:8001 --workers 4\n```\n\n## Establishing an SSE Connection with the Relay Service\n\n```javascript\nconst channelName = \"NOTIFICATIONS\"\nconst severURL = \"http://\u003cserver_host\u003e:\u003crelay_port\u003e\"\n\nconst eventSource = new EventSource(`${serverURL}/channel=${channelName}`);\n\neventSource.addEventListener('NEW_NOTIFICATION', (e) =\u003e {\n    console.log(e.data)\n})\n```\n\n## Sending Messages from Your Django App\n\nOnce you've installed this package in your Django project, you can use a simple `notify` function to send messages. This\nfunction works for both Redis and PostgreSQL.\n\n```python\nfrom sse_relay_server import notify\n\nnotify(\n    channel=\"Notifications\",\n    sse_payload={\n        \"event\": \"NEW_NOTIFICATION\",\n        \"id\": 1,\n        \"data\": json.dumps({\"message\": \"A new notification\"}),\n    },\n)\n```\n\n- `channel`: The PostgreSQL/Redis channel for sending the message.\n- `sse_payload`: A Python dictionary containing all the details of the SSE event. For a complete list of available\n  options, refer to [this class definition](https://github.com/sysid/sse-starlette/blob/main/sse_starlette/sse.py#L50).\n\nTo ensure smooth operation, avoid using excessively lengthy channel names, overly large payloads for PostgreSQL `NOTIFY`\nmessages, and bulky data for SSE event payloads, as there are size limitations for each of these aspects. If you need to\nretrieve a large database object, consider sending just the key and fetching the full data on the frontend using another\nrequest (such as an htmx request). While this extra request may not be the most ideal solution, for simplicity's sake,\nit's often a worthwhile trade-off.\n\nAt my workplace, we successfully implemented a straightforward real-time notification system using this approach,\ntransmitting all the necessary notification data without any issues. However, be aware of the potential risk of sending\noverly large data. For more in-depth information, you can refer to the following links:\n\n- [PostgreSQL NOTIFY](https://www.postgresql.org/docs/15/sql-notify.html)\n- [PostgreSQL LISTEN](https://www.postgresql.org/docs/current/sql-listen.html)\n- [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)\n- [Redis Pub/Sub](https://redis.io/topics/pubsub)\n\nIf for some reason you don't want or cannot install this package, the code for sending events for both PostgreSQL and\nRedis is quite simple, and you can easily copy and paste it from below.\n\n### Postgres\n\n```python\nimport json\nfrom django.db import connection\n\n\ndef notify(channel: str, sse_payload: dict) -\u003e None:\n    with connection.cursor() as cursor:\n        cursor.execute(f\"NOTIFY {channel}, '{json.dumps(sse_payload)}'\")\n```\n\n### Redis\n\n```python\nimport json\nimport redis\n\nREDIS_URL = \"redis://localhost:6379/0\"\n\n\ndef notify(channel: str, sse_payload: dict) -\u003e None:\n    r = redis.from_url(REDIS_URL)\n    r.publish(channel=channel, message=json.dumps(sse_payload))\n```\n\n## Stopping the SSE Connection\n\nAs far as I know, there is no standard method for stopping an established SSE connection. The most straightforward solution is to send a specific event, such as one named `STOP`, and handle it on the frontend.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftobi-de%2Fsse_relay_server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftobi-de%2Fsse_relay_server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftobi-de%2Fsse_relay_server/lists"}