本文整理汇总了Python中sseclient.SSEClient方法的典型用法代码示例。如果您正苦于以下问题:Python sseclient.SSEClient方法的具体用法?Python sseclient.SSEClient怎么用?Python sseclient.SSEClient使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sseclient
的用法示例。
在下文中一共展示了sseclient.SSEClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _streamSSE
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def _streamSSE(url, on_data=print, accrue=False):
'''internal'''
messages = SSEClient(url)
if accrue:
ret = []
for msg in messages:
data = msg.data
try:
on_data(json.loads(data))
if accrue:
ret.append(msg)
except PyEXStopSSE:
# stop listening and return
return ret
except (json.JSONDecodeError, KeyboardInterrupt):
raise
except Exception:
# continue listening
pass
return ret
示例2: Start
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def Start(self, callback):
client_id = self._config.client.writeback.client_id
client_id_hash = hashlib.sha1(client_id).hexdigest()
url_endpoint = "%s/%s.json" % (self.base, client_id_hash)
headers = {}
headers['Accept'] = 'text/event-stream'
while 1:
resp = self.get_requests_session().get(
url_endpoint, headers=headers, stream=True)
client = sseclient.SSEClient(resp)
for event in client.events():
# Ignore keep alive events.
if event.event in ['put', 'patch']:
self._session.logging.debug("FirebseNotifier woke up.")
callback(event.data)
self._session.logging.debug(
"Firebase connection reset, backing off.")
time.sleep(60)
示例3: test_event_stream
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def test_event_stream():
"""Check whether event.data can be loaded."""
limit = 50
url = 'https://stream.wikimedia.org/v2/stream/recentchange'
source = sseclient.SSEClient(url)
for n, event in enumerate(source, start=1):
if event.event != 'message' or not event.data:
continue
try:
element = json.loads(event.data)
except ValueError as e:
source.resp.close()
raise e
if n == limit:
break
assert True
示例4: __init__
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def __init__(
self,
url: str,
last_id: Union[str, int] = None,
retry: int = 3000,
session: Session = None,
chunk_size: int = 1024,
connect_retry: int = 0,
**kwargs
):
if SSEClient is None:
raise ImportError(
"SSE not supported, missing `stellar-base-sseclient` module"
) # pragma: no cover
self.client = SSEClient(
url, last_id, retry, session, chunk_size, connect_retry, **kwargs
)
示例5: _post
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def _post(self, url, fields=None, body=None):
r = self._http.request_encode_url('POST', url,
fields=fields, body=body,
preload_content=False)
if r.status != 200:
try:
if r.headers['Content-Type'] == 'application/json':
rbody = json.loads(r.read())
raise errors.SignalFlowException(
r.status,
rbody.get('message'),
rbody.get('errorType'))
raise errors.SignalFlowException(r.status)
finally:
r.close()
return sseclient.SSEClient(r)
示例6: thread_function
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def thread_function(self):
"""Thread function."""
self.__subscribed = True
url = SUBSCRIBE_ENDPOINT + "?token=" + self._session_token
data = self._session.query(url, method='GET', raw=True, stream=True)
if not data or not data.ok:
_LOGGER.debug("Did not receive a valid response. Aborting..")
return None
self.__sseclient = sseclient.SSEClient(data)
try:
for event in (self.__sseclient).events():
if not self.__subscribed:
break
data = json.loads(event.data)
if data.get('status') == "connected":
_LOGGER.debug("Successfully subscribed this base station")
elif data.get('action'):
action = data.get('action')
resource = data.get('resource')
if action == "logout":
_LOGGER.debug("Logged out by some other entity")
self.__subscribed = False
break
elif action == "is" and "subscriptions/" not in resource:
self.__events.append(data)
self.__event_handle.set()
except TypeError as error:
_LOGGER.debug("Got unexpected error: %s", error)
return None
return True
示例7: _query
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def _query(self, url, params=None, sse=False):
if not sse:
reply = self._session.get(url, params=params, timeout=self.request_timeout)
try:
return reply.json()
except ValueError:
raise Exception('invalid horizon reply: [{}] {}'.format(reply.status_code, reply.text))
# SSE connection
if SSEClient is None:
raise ValueError('SSE not supported, missing sseclient module')
return SSEClient(url, session=self._sse_session, params=params)
示例8: __init__
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def __init__(self, event_handler, heartbeat_handler, args):
self.connected = False
self.registered = False
self.queue = queue.Queue()
self.heartbeat_stop_event = threading.Event()
self.event_stream_stop_event = threading.Event()
self.arlo = args[0]
self.heartbeat_handler = heartbeat_handler
try:
event_stream = sseclient.SSEClient('https://my.arlo.com/hmsweb/client/subscribe?token='+self.arlo.request.session.headers.get('Authorization'), session=self.arlo.request.session)
self.event_stream_thread = threading.Thread(name="EventStream", target=event_handler, args=(self.arlo, event_stream, self.event_stream_stop_event, ))
self.event_stream_thread.setDaemon(True)
except Exception as e:
raise Exception('Failed to subscribe to eventstream: {0}'.format(e))
示例9: test_last_id_remembered
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def test_last_id_remembered(monkeypatch):
content = 'data: message 1\nid: abcdef\n\ndata: message 2\n\n'
fake_get = mock.Mock(return_value=FakeResponse(200, content))
monkeypatch.setattr(requests, 'get', fake_get)
c = sseclient.SSEClient('http://blah.com')
m1 = next(c)
m2 = next(c)
assert m1.id == 'abcdef'
assert m2.id is None
assert c.last_id == 'abcdef'
示例10: test_retry_remembered
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def test_retry_remembered(monkeypatch):
content = 'data: message 1\nretry: 5000\n\ndata: message 2\n\n'
fake_get = mock.Mock(return_value=FakeResponse(200, content))
monkeypatch.setattr(requests, 'get', fake_get)
c = sseclient.SSEClient('http://blah.com')
m1 = next(c)
m2 = next(c)
assert m1.retry == 5000
assert m2.retry is None
assert c.retry == 5000
示例11: test_extra_newlines_after_event
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def test_extra_newlines_after_event(monkeypatch):
"""
This makes sure that extra newlines after an event don't
cause the event parser to break as it did in
https://github.com/btubbs/sseclient/issues/5.
"""
content = """event: hello
data: hello1
event: hello
data: hello2
event: hello
data: hello3
"""
fake_get = mock.Mock(return_value=FakeResponse(200, content))
monkeypatch.setattr(requests, 'get', fake_get)
c = sseclient.SSEClient('http://blah.com')
m1 = next(c)
m2 = next(c)
m3 = next(c)
assert m1.event == 'hello'
assert m1.data == 'hello1'
assert m2.data == 'hello2'
assert m2.event == 'hello'
assert m3.data == 'hello3'
assert m3.event == 'hello'
示例12: test_multiple_messages
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def test_multiple_messages():
c = sseclient.SSEClient('http://blah.com')
m1 = next(c)
m2 = next(c)
m3 = next(c)
assert_multiple_messages(m1, m2, m3)
assert c.retry == m2.retry
assert c.last_id == m3.id
示例13: test_simple_iteration
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def test_simple_iteration():
c = sseclient.SSEClient('http://blah.com')
m1, m2, m3 = itertools.islice(c, 3)
assert_multiple_messages(m1, m2, m3)
示例14: __enter__
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def __enter__(self):
url = self.endpoint
if self.from_time is not None:
url += '?since='+self.from_time.isoformat().replace('+00:00', 'Z')
self.stream = SSEClient(url)
return self
示例15: listen
# 需要导入模块: import sseclient [as 别名]
# 或者: from sseclient import SSEClient [as 别名]
def listen(self, events=None, **kwargs):
# Late import to avoid very expensive in-direct import (~1 second) when this function is
# not called / used
from sseclient import SSEClient
url = self._url
query_params = {}
request_params = {}
if events and isinstance(events, six.string_types):
events = [events]
if 'token' in kwargs:
query_params['x-auth-token'] = kwargs.get('token')
if 'api_key' in kwargs:
query_params['st2-api-key'] = kwargs.get('api_key')
if events:
query_params['events'] = ','.join(events)
if self.cacert is not None:
request_params['verify'] = self.cacert
query_string = '?' + urllib.parse.urlencode(query_params)
url = url + query_string
response = requests.get(url, stream=True, **request_params)
client = SSEClient(response)
for message in client.events():
# If the execution on the API server takes too long, the message
# can be empty. In this case, rerun the query.
if not message.data:
continue
yield json.loads(message.data)