Skip to content

Instantly share code, notes, and snippets.

@Thewest123
Last active December 22, 2024 12:41
Show Gist options
  • Save Thewest123/178b2df41ff14385d8940680e0ca9833 to your computer and use it in GitHub Desktop.
Save Thewest123/178b2df41ff14385d8940680e0ca9833 to your computer and use it in GitHub Desktop.
Spoolman API - Update weight with Python
# A simple CLI tool to interact with the Spoolman REST API
# Simply just select the spool ID and enter the used weight to update the spool
import requests
import os
# Base API URL
BASE_URL = "https://spoolman.local/api/v1"
# Reset to default color
RESET_COLOR = "\033[0m"
# Fetch the list of available spools
def fetch_spools():
try:
response = requests.get(f"{BASE_URL}/spool")
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching spools: {e}")
return None
# Function to convert hex color to ANSI escape code
def hex_to_ansi(hex_color):
# Remove the '#' if present
hex_color = hex_color.lstrip("#")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
# 24-bit RGB color
return f"\033[38;2;{r};{g};{b}m"
# Print available spools details
def print_spools(spools):
# Calculate the max widths of columns
name_max_width = max(
len(f"{spool['filament']['vendor']['name']} {spool['filament']['name']}")
for spool in spools
)
material_max_width = max(
len(f"{spool['filament']['material']}")
for spool in spools
)
for spool in spools:
filament = spool['filament']
vendor = filament['vendor']
name = f"{vendor['name']} {filament['name']}"
material = filament['material']
color_code = hex_to_ansi(filament['color_hex'])
print(f"#{spool['id']:2d} | {color_code}■{RESET_COLOR} {name.ljust(name_max_width)} | {material.ljust(material_max_width)} | {spool['remaining_weight']:.2f}g")
print("")
# Send used weight to the API
def update_spool(spool_id, used_weight):
url = f"{BASE_URL}/spool/{spool_id}/use"
payload = {"use_weight": used_weight}
try:
response = requests.put(url, json=payload)
response.raise_for_status()
return response.json(), ""
except requests.exceptions.RequestException as e:
return None, f"Error updating spool: {e}"
# Main script logic
def main():
message = ""
while(True):
spools = fetch_spools()
if not spools:
return
# Clear the terminal
# os.system("clear") # Linux
os.system("cls") # Windows
# Print spools
print_spools(spools)
print(message)
print("")
try:
# Ask for the spool ID to interact with
spool_id = int(input("Enter the Spool ID to update (0 to quit): "))
# Quit if the user enters 0
if spool_id == 0:
print("Goodbye!")
return
# Ask for the used weight
used_weight = float(input("Enter the used weight (in grams): "))
# Send PUT request to update the spool with the used weight
updated_spool, message = update_spool(spool_id, used_weight)
if updated_spool:
message = f"Updated Spool ID {spool_id} successfully. \nRemaining weight: {updated_spool['remaining_weight']}g"
except ValueError:
message = "Invalid input. Please enter valid numbers for Spool ID and used weight"
if __name__ == "__main__":
main()
@Thewest123
Copy link
Author

Preview with colors and better formatting :)
WindowsTerminal_sdt9bOBq2T

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment