-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrest_client.py
More file actions
129 lines (104 loc) · 3.92 KB
/
rest_client.py
File metadata and controls
129 lines (104 loc) · 3.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""
Uptime Kuma REST API Client
Handles REST API interactions with Uptime Kuma.
"""
import requests
from typing import Optional, Dict, Any
from urllib.parse import urljoin
import base64
class UptimeKumaRESTClient:
"""
REST API client for Uptime Kuma.
Handles authentication and REST endpoint interactions.
"""
def __init__(self, base_url: str, username: Optional[str] = None,
password: Optional[str] = None, api_key: Optional[str] = None):
"""
Initialize the REST client.
Args:
base_url: Base URL of the Uptime Kuma instance
username: Username for basic auth (optional if using API key)
password: Password for basic auth (optional if using API key)
api_key: API key for authentication (optional if using username/password)
"""
self.base_url = base_url.rstrip('/')
self.username = username
self.password = password
self.api_key = api_key
self.session = requests.Session()
# Set up authentication
if api_key:
# API key authentication for metrics endpoint
self.session.headers.update({
'Authorization': f'Bearer {api_key}'
})
elif username and password:
# Basic auth for metrics endpoint
auth_string = base64.b64encode(f"{username}:{password}".encode()).decode()
self.session.headers.update({
'Authorization': f'Basic {auth_string}'
})
def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
"""Make HTTP request and handle common response processing."""
url = urljoin(self.base_url + '/', endpoint.lstrip('/'))
response = self.session.request(method, url, **kwargs)
response.raise_for_status()
# Handle different response types
if response.headers.get('content-type', '').startswith('application/json'):
return response.json()
else:
return {'content': response.text, 'status_code': response.status_code}
def push_monitor_status(self, push_token: str, status: str = "up",
msg: str = "OK", ping: Optional[float] = None) -> Dict[str, Any]:
"""
Push status update for a monitor.
Args:
push_token: The push token for the monitor
status: Status ("up" or "down")
msg: Status message
ping: Response time in milliseconds (optional)
Returns:
API response
"""
params = {'status': status, 'msg': msg}
if ping is not None:
params['ping'] = ping
return self._make_request('GET', f'api/push/{push_token}', params=params)
def get_status_page(self, slug: str) -> Dict[str, Any]:
"""
Get status page data.
Args:
slug: Status page slug
Returns:
Status page data
"""
return self._make_request('GET', f'api/status-page/{slug}')
def get_status_page_heartbeat(self, slug: str) -> Dict[str, Any]:
"""
Get status page heartbeat data.
Args:
slug: Status page slug
Returns:
Heartbeat data
"""
return self._make_request('GET', f'api/status-page/heartbeat/{slug}')
def get_metrics(self) -> str:
"""
Get Prometheus metrics.
Returns:
Metrics in Prometheus format
"""
response = self._make_request('GET', 'metrics')
if isinstance(response, dict) and 'content' in response:
return response['content']
return str(response)
def get_entry_page(self) -> Dict[str, Any]:
"""
Get entry page information.
Returns:
Entry page data
"""
return self._make_request('GET', 'api/entry-page')
def close(self):
"""Close the session."""
self.session.close()