请求提供基于PySimpleGUI的API心跳检测UI入门示例代码
PySimpleGUI API Heartbeat Monitor Example
Hey there! Since you're new to PySimpleGUI, I've whipped up a straightforward, easy-to-modify code example that fits your requirements perfectly. This will create a simple UI showing the status of two APIs, checking them every 5 minutes (300 seconds) and updating the display to "OK" or "NOT OK" based on the response.
import PySimpleGUI as sg import requests import time def check_api_status(api_url): """Check if the API is reachable and returns a successful response""" try: # Send a GET request (adjust method/headers if your API needs it) response = requests.get(api_url, timeout=10) # Consider it OK if status code is in the 2xx range if 200 <= response.status_code < 300: return "OK" else: return "NOT OK" except Exception: # Any error (connection issue, timeout, etc.) means the API is unreachable return "NOT OK" # Define the UI layout layout = [ [sg.Text("API 1 - ", size=(10, 1)), sg.Text("Loading...", key="-STATUS1-", size=(8, 1))], [sg.Text("API 2 - ", size=(10, 1)), sg.Text("Loading...", key="-STATUS2-", size=(8, 1))], [sg.Button("Exit", size=(10, 1))] ] # Create the main window window = sg.Window("API Heartbeat Monitor", layout) # Set check interval (5 minutes = 300 seconds) CHECK_INTERVAL = 300 last_check_timestamp = 0 # Main event loop while True: # Check for events every 1 second to keep UI responsive event, values = window.read(timeout=1000) # Exit if window is closed or Exit button is clicked if event == sg.WIN_CLOSED or event == "Exit": break # Run API checks if the interval has passed current_time = time.time() if current_time - last_check_timestamp >= CHECK_INTERVAL: # Update status for API 1 status_1 = check_api_status("https://your-api-endpoint-1.com/heartbeat") # Replace with your URL window["-STATUS1-"].update(status_1) # Update status for API 2 status_2 = check_api_status("https://your-api-endpoint-2.com/heartbeat") # Replace with your URL window["-STATUS2-"].update(status_2) last_check_timestamp = current_time # Clean up and close the window window.close()
Key Details to Customize:
- API Endpoints: Replace the example URLs in
check_api_status()calls with your actual API heartbeat endpoints. - Request Configuration: If your API requires POST requests, headers, or authentication, modify the
requests.get()line (e.g., addheaders={"Authorization": "Bearer YOUR_TOKEN"}). - Check Frequency: Adjust
CHECK_INTERVALto change how often the APIs are checked (value is in seconds). - Status Logic: Modify the
check_api_status()function if you need to validate specific response content instead of just status codes.
内容的提问来源于stack exchange,提问作者Henry
相关产品推荐
相关产品推荐

