Spaces:
Runtime error
Runtime error
import os | |
import requests | |
import json | |
# --- Constants --- | |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" | |
QUESTIONS_FILE = "questions.json" | |
def fetch_and_save_questions(): | |
""" | |
Fetches questions from the API and saves them to a JSON file. | |
""" | |
questions_url = f"{DEFAULT_API_URL}/questions" | |
print(f"Fetching questions from: {questions_url}") | |
try: | |
response = requests.get(questions_url, timeout=15) | |
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx) | |
questions_data = response.json() | |
if not questions_data: | |
print("Fetched questions list is empty or invalid format.") | |
return | |
print(f"Fetched {len(questions_data)} questions.") | |
# Save the questions to a JSON file | |
with open(QUESTIONS_FILE, 'w', encoding='utf-8') as f: | |
json.dump(questions_data, f, indent=4) | |
print(f"Successfully saved questions to {QUESTIONS_FILE}") | |
except requests.exceptions.RequestException as e: | |
print(f"Error fetching questions: {e}") | |
except requests.exceptions.JSONDecodeError as e: | |
print(f"Error decoding JSON response from questions endpoint: {e}") | |
if 'response' in locals() and response is not None: | |
print(f"Response text (first 500 chars): {response.text[:500]}") | |
except IOError as e: | |
print(f"Error saving questions to file: {e}") | |
except Exception as e: | |
print(f"An unexpected error occurred: {e}") | |
if __name__ == "__main__": | |
print("--- Starting Question Fetcher ---") | |
fetch_and_save_questions() | |
print("--- Question Fetcher Finished ---") | |