UtopiaHarvester Python GUI
👤 Sharing: AI
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import requests
import json
import threading
import time
class UtopiaHarvesterGUI:
def __init__(self, master):
self.master = master
master.title("Utopia Harvester")
master.geometry("800x600")
self.api_url_label = ttk.Label(master, text="API Endpoint URL:")
self.api_url_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.api_url_entry = ttk.Entry(master, width=60)
self.api_url_entry.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
self.api_url_entry.insert(0, "https://your-api-endpoint.com/data") # Placeholder
self.query_params_label = ttk.Label(master, text="Query Parameters (JSON format):")
self.query_params_label.grid(row=1, column=0, padx=5, pady=5, sticky="nw")
self.query_params_text = scrolledtext.ScrolledText(master, width=60, height=5)
self.query_params_text.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
self.query_params_text.insert("1.0", "{\n \"param1\": \"value1\",\n \"param2\": 123\n}") # Placeholder
self.headers_label = ttk.Label(master, text="Headers (JSON format):")
self.headers_label.grid(row=2, column=0, padx=5, pady=5, sticky="nw")
self.headers_text = scrolledtext.ScrolledText(master, width=60, height=3)
self.headers_text.grid(row=2, column=1, padx=5, pady=5, sticky="ew")
self.headers_text.insert("1.0", "{\n \"Content-Type\": \"application/json\",\n \"Authorization\": \"Bearer YOUR_API_KEY\"\n}") # Placeholder
self.polling_interval_label = ttk.Label(master, text="Polling Interval (seconds):")
self.polling_interval_label.grid(row=3, column=0, padx=5, pady=5, sticky="w")
self.polling_interval_entry = ttk.Entry(master, width=10)
self.polling_interval_entry.grid(row=3, column=1, padx=5, pady=5, sticky="w")
self.polling_interval_entry.insert(0, "60") # Default: 60 seconds
self.start_button = ttk.Button(master, text="Start Harvesting", command=self.start_harvesting)
self.start_button.grid(row=4, column=0, columnspan=2, padx=5, pady=10)
self.stop_button = ttk.Button(master, text="Stop Harvesting", command=self.stop_harvesting, state=tk.DISABLED)
self.stop_button.grid(row=4, column=1, columnspan=2, padx=5, pady=10)
self.output_label = ttk.Label(master, text="Harvested Data:")
self.output_label.grid(row=5, column=0, padx=5, pady=5, sticky="nw")
self.output_text = scrolledtext.ScrolledText(master, width=80, height=15)
self.output_text.grid(row=5, column=1, padx=5, pady=5, sticky="ew")
self.details_button = ttk.Button(master, text="Details", command=self.show_details)
self.details_button.grid(row=6, column=0, columnspan=2, padx=5, pady=10)
self.is_running = False
self.harvesting_thread = None
master.grid_columnconfigure(1, weight=1) # Make the second column expandable
master.grid_rowconfigure(5, weight=1) # Make the output text area expandable
def start_harvesting(self):
if self.is_running:
messagebox.showerror("Error", "Harvesting is already running.")
return
try:
self.api_url = self.api_url_entry.get()
self.query_params = json.loads(self.query_params_text.get("1.0", tk.END))
self.headers = json.loads(self.headers_text.get("1.0", tk.END))
self.polling_interval = int(self.polling_interval_entry.get())
if self.polling_interval <= 0:
raise ValueError("Polling interval must be a positive number.")
except json.JSONDecodeError:
messagebox.showerror("Error", "Invalid JSON format in Query Parameters or Headers.")
return
except ValueError as e:
messagebox.showerror("Error", str(e))
return
self.is_running = True
self.start_button.config(state=tk.DISABLED)
self.stop_button.config(state=tk.NORMAL)
self.harvesting_thread = threading.Thread(target=self.harvest_data, daemon=True)
self.harvesting_thread.start()
def stop_harvesting(self):
self.is_running = False
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
def harvest_data(self):
while self.is_running:
try:
response = requests.get(self.api_url, params=self.query_params, headers=self.headers)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
data = response.json()
self.display_data(data)
except requests.exceptions.RequestException as e:
self.display_error(f"Request Error: {e}")
except json.JSONDecodeError:
self.display_error("Error: Invalid JSON response from API.")
except Exception as e:
self.display_error(f"Unexpected Error: {e}")
time.sleep(self.polling_interval)
def display_data(self, data):
formatted_data = json.dumps(data, indent=2)
self.output_text.insert(tk.END, f"\n---\n{formatted_data}\n")
self.output_text.see(tk.END) # Scroll to the end
def display_error(self, error_message):
self.output_text.insert(tk.END, f"\n---\nError: {error_message}\n")
self.output_text.see(tk.END)
def show_details(self):
details_text = """
Utopia Harvester is a versatile data extraction tool designed to periodically fetch data from a specified API endpoint. It is highly configurable and suitable for monitoring real-time data streams or collecting data for analysis.
Key Features:
* **Configurable API Endpoint:** Specify the exact API URL to retrieve data from.
* **Query Parameters:** Define query parameters in JSON format to customize the API request.
* **Custom Headers:** Set custom headers, such as authentication tokens, to interact with secured APIs.
* **Polling Interval:** Configure the frequency at which the API is polled for new data.
* **Error Handling:** Robust error handling to gracefully manage network issues, invalid JSON responses, and other exceptions.
* **Real-time Display:** Displays the harvested data in a scrollable text area, allowing you to monitor the data stream in real-time.
* **JSON Formatting:** Automatically formats the JSON data for easy readability.
* **Threaded Operation:** Uses a separate thread to perform data harvesting, preventing the GUI from freezing.
How to Use:
1. Enter the API Endpoint URL in the 'API Endpoint URL' field.
2. Enter any necessary query parameters in JSON format in the 'Query Parameters' field.
3. Enter any required headers in JSON format in the 'Headers' field (e.g., Content-Type, Authorization).
4. Set the desired polling interval (in seconds) in the 'Polling Interval' field.
5. Click 'Start Harvesting' to begin data collection.
6. Click 'Stop Harvesting' to halt data collection.
Notes:
* The API endpoint should return data in JSON format.
* Ensure that the query parameters and headers are valid JSON.
* A higher polling interval reduces the load on the API server but may result in less frequent updates.
* Error messages will be displayed in the output area.
This tool is designed for developers, data analysts, and anyone who needs to monitor or collect data from APIs on a regular basis. Please use responsibly and respect the terms of service of the API you are accessing.
"""
messagebox.showinfo("Details", details_text)
root = tk.Tk()
gui = UtopiaHarvesterGUI(root)
root.mainloop()
👁️ Viewed: 5
Comments