Created
April 19, 2021 15:13
-
-
Save angrycub/016d17fd83af504a0ed06e0f1fc30448 to your computer and use it in GitHub Desktop.
Minimal Python Client for Nomad Event Stream
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
import json | |
import requests | |
import sys | |
URL_BASE = "http://127.0.0.1:4646" | |
URL_API_PATH = "/v1/event/stream" | |
URL_QUERY_STRING = "" | |
#URL.QUERY_STRING = "?topic=Node:*" | |
url = URL_BASE + URL_API_PATH + URL_QUERY_STRING | |
def handle_event(event): | |
print("topic: "+ event["Topic"]+ " type: " + event["Type"]) | |
def handle_data(response): | |
''' | |
Handle a single line of data from the HTTP stream. | |
''' | |
for line in response.iter_lines(): | |
if line: # filter out keep-alive new lines | |
object = json.loads(line.decode('utf-8')) | |
if len(object) > 1: # has Events | |
for event in object["Events"]: | |
handle_event(event) | |
def connect(url): | |
try: | |
response = requests.get(url, stream=True) | |
response.raise_for_status() | |
handle_data(response) | |
except requests.exceptions.RequestException as e: # This is the correct syntax | |
raise SystemExit(e) | |
def start(): | |
try: | |
connect(url) | |
except KeyboardInterrupt: | |
print("Received keyboard interrupt. Stopping.") | |
SystemExit() | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment