A simple asynchronous Server Sent Events (SSE) client for Python.
For more information about Server Sent Events, refer to MDN Web Docs.
Install the package using pip:
pip install py-sse-clientimport asyncio
import pysse
def listener(event):
print(event)
async def main():
client = pysse.Client("https://example.com/sse", listener)
await client.connect()
if __name__ == "__main__":
asyncio.run(main())To create a client, use the Client class. The constructor accepts the following arguments:
url:- The URL of the SSE endpoint
- Type:
str - Required
callable:- A callback function that will be invoked whenever an event is received
- The callback receives an
Eventobject as its argument - Type:
Callable - Required
param:- Query parameters to include in the request
- Default is an empty dictionary
- Type:
dict - Optional
headers:- HTTP headers to include in the request
- Default is an empty dictionary
- Type:
dict - Optional
Example:
from pysse import Client
def listener(event):
print(f"Event Name: {event.name}")
print(f"Event Data: {event.data}")
client = Client(
url="https://example.com/sse",
callable=listener,
param={"token": "your_token"},
headers={"Authorization": "Bearer your_token"}
)To connect to the SSE API, call the connect method of the Client instance. This method is asynchronous and should be awaited.
Example:
import asyncio
async def main():
await client.connect()
asyncio.run(main())To disconnect from the SSE API, call the close method of the Client instance. This method is also asynchronous and should be awaited.
Example:
async def main():
await client.close()
asyncio.run(main())Constructor
Client(url: str, callable: Callable, param: dict = {}, headers: dict = {})Arguments:
url(str): The URL of the SSE endpointcallable(Callable): A callback function to handle incoming eventsparam(dict, optional): Query parameters for the requestheaders(dict, optional): HTTP headers for the request
Methods
-
async connect() -> None
Connects to the SSE API and starts listening for events -
async close() -> None
Disconnects from the SSE API -
is_closed() -> bool
ReturnsTrueif the connection is closed, otherwiseFalse
A data class representing an SSE event
Attributes:
name(str): The name of the eventdata(dict): The data associated with the event
This project is licensed under the MIT License. See the LICENSE file for details.