whereis-client/main.py
2024-12-18 09:39:16 +01:00

104 lines
3.2 KiB
Python

import logging
import sys
import json
import time
from src import VERSION, Client, OrderField
from src.exceptions import WhereIsException, UnauthorizedException
stdout_handler = logging.StreamHandler(stream=sys.stdout)
logging.basicConfig(
format="[%(levelname)s] - %(asctime)s - %(message)s",
level=logging.INFO,
handlers=(stdout_handler,),
)
if __name__ == "__main__":
"""
This a sample script to demonstrate how works WhereIs API client.
All you need is to provide some environments variables describe in the `.env.example`.
You can:
- Copy `.env.example` into `.env` and feed env variables or,
- Directly export those mandatories variables
Once its done, you can initialize the Client:
cli = Client.from_env()
and use all the available methods to interact with the WhereIs API.
Sessions:
- create_session
- get_sessions
- get_session
- update_session
- delete_session
- update_session_users
- close_session
- watch_session_events
- stop_watch_session
"""
logging.info(f"WhereIs client v{VERSION}")
# initialize the client
try:
cli = Client.from_env()
except WhereIsException as e:
logging.error(f"unable to initialize WhereIs API client: {e}")
except Exception as e:
logging.error("unexpected error occurred while initializing client", exc_info=True)
# retrieve all user/public sessions
sessions = cli.get_sessions()
print(json.dumps(sessions, indent=2))
# create and update a session (must have `Streamer` role)
try:
session = cli.create_session(name="RUN-01")
session = cli.update_session(session.get("id"), name="RUN-02", description="My second run")
except WhereIsException as e:
logging.error(f"error occurred while creating/updating a session, status code: {e.error_code}")
print(json.dumps(e.content, indent=2))
# retrieve all user/public sessions with ordering
sessions = cli.get_sessions(ordering=OrderField.AscDateStart)
print(json.dumps(sessions, indent=2))
# retrieve all user/public sessions with search
sessions = cli.get_sessions(search="run", ordering=OrderField.AscDateStart)
print(json.dumps(sessions, indent=2))
# retrieve session by id
session = cli.get_session(session.get("id"))
print(json.dumps(session, indent=2))
# update session users
try:
session = cli.update_session_users(session.get("id"), [])
except WhereIsException as e:
logging.error(f"error occurred while updating users session, status code: {e.error_code}")
print(json.dumps(e.content, indent=2))
# close a session
try:
session = cli.close_session("does-not-exist")
except WhereIsException as e:
logging.error(f"error occurred while updating users session, status code: {e.error_code}")
print(json.dumps(e.content, indent=2))
# get session events
cli.watch_session_events(session.get("id"))
# doing your stuff...
time.sleep(5)
# close the session
session = cli.close_session(session.get("id"))
# delete a session
cli.delete_session(session.get("id"))
# stop session events watcher
cli.stop_watch_session(session.get("id"))