load-balancer / api.py
ChandimaPrabath's picture
patch 2
83371d8
import requests
import logging
from urllib.parse import quote
class InstancesAPI:
def __init__(self, instances):
self.instances = instances
def fetch_reports(self):
reports = {}
for instance_url in self.instances:
try:
response = requests.get(f"{instance_url}/api/get/report")
response.raise_for_status()
reports[instance_url] = response.json()
except requests.exceptions.RequestException as e:
logging.error(f"Error contacting instance {instance_url}: {e}")
return reports
def download_music(self, instance_url, title):
"""
Download a music file to an instance.
If the download starts, it returns a JSON like this:
example:
{"music_id": "song_title_2024",
"status": "Download started"}
If the music file has already been downloaded, it will return the audio file.
"""
data = {}
try:
# URL-encode the title to handle special characters
encoded_title = quote(title)
response = requests.get(f"{instance_url}/api/get/music/{encoded_title}")
response.raise_for_status()
data = response.json()
except requests.exceptions.RequestException as e:
logging.error(f"Error contacting instance {instance_url}: {e}")
data = {"error": str(e)}
return data