Providing SSE and long-polling Python examples with delta updates
Here's Python code demonstrating how to receive live sports updates via SSE using the sseclient-py library and via long polling with requests. Both maintain previous game state to print only score changes or goal events, minimizing console noise.
# SSE example using sseclient-py
# Install with: pip install sseclient-py requests
import json
import requests
import sseclient
SSE_URL = "https://example.com/sports/scores/stream" # replace with actual SSE endpoint
def sse_live_scores():
state = {} # {match_id: {"score": ..., "last_event": ...}}
# Open SSE stream
response = requests.get(SSE_URL, stream=True)
client = sseclient.SSEClient(response)
for event in client.events():
if not event.data:
continue
try:
data = json.loads(event.data)
except json.JSONDecodeError:
continue
match_id = data.get("match_id")
if not match_id:
continue
prev = state.get(match_id, {})
# Detect score changes
if data.get("score") != prev.get("score"):
print(f"Score update for match {match_id}: {data['score']}")
# Detect goal events (or any other event type you'd like)
if event.event == "goal":
scorer = data.get("scorer", "Unknown")
print(f"Goal! {scorer} scored in match {match_id}")
# Update state
state[match_id] = data
# Long-polling example using requests
import time
LONG_POLL_URL = "https://example.com/sports/scores" # replace with actual API endpoint
def long_poll_live_scores(poll_interval=5):
state = {}
headers = {}
while True:
try:
response = requests.get(LONG_POLL_URL, headers=headers, timeout=30)
if response.status_code == 200:
scores = response.json() # Assume JSON list of matches
for match in scores:
match_id = match.get("match_id")
if not match_id:
continue
prev = state.get(match_id, {})
# Compare scores and notify changes
if match.get("score") != prev.get("score"):
print(f"Score update for match {match_id}: {match['score']}")
# Optionally check for recent goals or events here
state[match_id] = match
# Optionally use headers like ETag or Last-Modified to optimize
if "ETag" in response.headers:
headers["If-None-Match"] = response.headers["ETag"]
if "Last-Modified" in response.headers:
headers["If-Modified-Since"] = response.headers["Last-Modified"]
elif response.status_code == 304:
# No changes
pass
except requests.RequestException:
# Network or timeout error, ignore and retry
pass
time.sleep(poll_interval)
if __name__ == "__main__":
# Uncomment one to run
# sse_live_scores()
# long_poll_live_scores()
pass
This code outlines connecting to live updates and printing only changes by storing previous states for each match. Replace URLs with actual endpoints and adjust parsing logic as needed.
Below is a simple pattern you can adapt for either SSE (Server-Sent Events) or a polling API. It maintains a local previous_state dictionary and prints only when scores change or a special event (like a goal) occurs.
1) SSE Example (Python)
Make sure your server supports SSE and returns JSON payloads. You can use the sseclient package to parse the stream.
import json
import time
import requests
from sseclient import SSEClient
SSE_URL = "https://example.com/live-scores" # replace with your SSE endpoint
def process_event(data_str, previous_state):
"""
Expects data_str to be JSON with a structure like:
{
"matches": [
{
"id": "match123",
"home": "Team A",
"away": "Team B",
"score": {"home": 1, "away": 2},
"last_event": "Goal by Player X"
},
...
]
}
Adjust accordingly to your actual API shape.
"""
try:
payload = json.loads(data_str)
except json.JSONDecodeError:
return
for match in payload.get("matches", []):
match_id = match["id"]
new_score = match["score"]
last_event = match.get("last_event")
old_match = previous_state.get(match_id)
if old_match:
# Compare scores
old_score = old_match["score"]
if new_score != old_score:
print(f"[Score Update] {match['home']} {new_score['home']} - {new_score['away']} {match['away']}")
# Print goal or special event if changed
old_event = old_match.get("last_event")
if last_event and last_event != old_event:
print(f"[Event] {match['home']} vs {match['away']}: {last_event}")
else:
# New match discovered
print(f"[New Match] {match['home']} vs {match['away']}")
print(f"Score: {new_score['home']} - {new_score['away']}")
if last_event:
print(f"[Event] {last_event}")
# Update stored state
previous_state[match_id] = match
def main_sse():
previous_state = {}
while True:
try:
# Create a fresh EventSource connection
# (some servers may need periodic reconnects)
messages = SSEClient(SSE_URL)
for msg in messages:
if msg.data and msg.event != 'keep-alive':
process_event(msg.data, previous_state)
except Exception as e:
# On connection error, wait and try again
print("SSE connection error, retrying:", e)
time.sleep(3)
if __name__ == "__main__":
main_sse()
Notes:
- Replace
SSE_URL with the actual endpoint.
- Adjust the JSON parsing (
process_event) according to your SSE server’s event data.
- We ignore keep-alive events. Any time we see a score change or a new event string, we print it. Otherwise, we keep quiet.
2) Long-Polling Example (Python)
If SSE isn’t available, you can simulate “push” by frequently polling for new data with ETag or If-Modified-Since headers to reduce bandwidth. Below is a bare-bones approach without caching headers (you can add them depending on your API).
import json
import time
import requests
POLL_URL = "https://example.com/live-scores" # replace with your API endpoint
POLL_INTERVAL = 5 # seconds
def process_payload(payload, previous_state):
# Same logic as the SSE example
for match in payload.get("matches", []):
match_id = match["id"]
new_score = match["score"]
last_event = match.get("last_event")
old_match = previous_state.get(match_id)
if old_match:
old_score = old_match["score"]
if new_score != old_score:
print(f"[Score Update] {match['home']} {new_score['home']} - {new_score['away']} {match['away']}")
old_event = old_match.get("last_event")
if last_event and last_event != old_event:
print(f"[Event] {match['home']} vs {match['away']}: {last_event}")
else:
print(f"[New Match] {match['home']} vs {match['away']}")
print(f"Score: {new_score['home']} - {new_score['away']}")
if last_event:
print(f"[Event] {last_event}")
previous_state[match_id] = match
def main_poll():
previous_state = {}
while True:
try:
resp = requests.get(POLL_URL, timeout=10)
resp.raise_for_status()
payload = resp.json() # expecting JSON
process_payload(payload, previous_state)
except Exception as e:
print("Polling error:", e)
time.sleep(POLL_INTERVAL)
if __name__ == "__main__":
main_poll()
Tips for Polling:
- If your server supports
ETag/If-None-Match or If-Modified-Since, include those headers to avoid fetching unchanged data.
- Use exponential backoff or shorter intervals depending on how frequently the server updates.
- The
previous_state dict avoids printing repeated info; only differences get logged.
Summary:
- For SSE: open a streaming connection, parse each event’s data as JSON, compare with your stored
previous_state, and print only when there’s a change.
- For long-polling: fetch regularly, parse JSON, and do the same delta comparison.
Swap in your real endpoint and JSON structure, and you’ll get quiet, incremental updates (e.g., only showing new goals or new scores).