-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* #61 SSE streaming manager * Remove extraneous import * isort fixes * Self CR * CR changes * Simplify Flagsmith.__init__ to keep flake8 happy * Remove extraneous noqa * Adds typing to new methods and tests * Remove typing.TypeAlias Incompatible with python <= 3.9 * Use Optional as opposed to pipe
- Loading branch information
Showing
7 changed files
with
533 additions
and
154 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import logging | ||
import threading | ||
from typing import Callable, Generator, Optional, Protocol, cast | ||
|
||
import requests | ||
import sseclient | ||
|
||
from flagsmith.exceptions import FlagsmithAPIError | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class StreamEvent(Protocol): | ||
data: str | ||
|
||
|
||
class EventStreamManager(threading.Thread): | ||
def __init__( | ||
self, | ||
*args, | ||
stream_url: str, | ||
on_event: Callable[[StreamEvent], None], | ||
request_timeout_seconds: Optional[int] = None, | ||
**kwargs | ||
) -> None: | ||
super().__init__(*args, **kwargs) | ||
self._stop_event = threading.Event() | ||
self.stream_url = stream_url | ||
self.on_event = on_event | ||
self.request_timeout_seconds = request_timeout_seconds | ||
|
||
def run(self) -> None: | ||
while not self._stop_event.is_set(): | ||
try: | ||
with requests.get( | ||
self.stream_url, | ||
stream=True, | ||
headers={"Accept": "application/json, text/event-stream"}, | ||
timeout=self.request_timeout_seconds, | ||
) as response: | ||
sse_client = sseclient.SSEClient( | ||
cast(Generator[bytes, None, None], response) | ||
) | ||
for event in sse_client.events(): | ||
self.on_event(event) | ||
|
||
except requests.exceptions.ReadTimeout: | ||
pass | ||
|
||
except (FlagsmithAPIError, requests.RequestException): | ||
logger.exception("Error handling event stream") | ||
|
||
def stop(self) -> None: | ||
self._stop_event.set() | ||
|
||
def __del__(self) -> None: | ||
self._stop_event.set() |
Oops, something went wrong.