ocngx / examples.py
tanbushi's picture
update
5e15438
Raw
History Blame
5.68 kB
"""
Usage examples for the OpenResty API client
This module demonstrates various ways to use the API client
including basic usage, error handling, and advanced scenarios.
"""
from api_client import APIClient, create_client, APIClientError, NetworkError, AuthenticationError
from config import get_connection_params
def basic_usage():
"""Basic usage example"""
print("=== Basic Usage Example ===")
# Method 1: Direct instantiation
client = APIClient(
base_url="https://airsltd-ocngx.hf.space",
username="admin",
password="admin123"
)
try:
# Get main page
response = client.get("/")
print(f"Status: {response['status']}")
print(f"Status Code: {response['status_code']}")
print(f"Data: {response['data']}")
# Health check
health = client.health_check()
print(f"Health Status: {health['status']}")
print(f"Health Message: {health['message']}")
except Exception as e:
print(f"Error: {e}")
finally:
client.close()
def convenience_function():
"""Using the convenience create_client function"""
print("\n=== Convenience Function Example ===")
client = create_client()
try:
response = client.get("/")
print(f"Response: {response}")
health = client.health_check()
print(f"Health: {health}")
except Exception as e:
print(f"Error: {e}")
finally:
client.close()
def context_manager_example():
"""Using context manager for automatic cleanup"""
print("\n=== Context Manager Example ===")
try:
with create_client() as client:
response = client.get("/")
print(f"Response: {response['status']}")
health = client.health_check()
print(f"Health: {health['status']}")
# Session is automatically closed here
except Exception as e:
print(f"Error: {e}")
def error_handling_examples():
"""Demonstrate different error handling scenarios"""
print("\n=== Error Handling Examples ===")
# Test with invalid credentials
try:
with APIClient(
base_url="https://airsltd-ocngx.hf.space",
username="admin",
password="wrongpassword" # Invalid password
) as client:
response = client.get("/")
print(f"This shouldn't print: {response}")
except AuthenticationError as e:
print(f"Authentication Error: {e.message}")
print(f"Status Code: {e.status_code}")
except Exception as e:
print(f"Other Error: {e}")
# Test with invalid URL
try:
with APIClient(
base_url="https://invalid-url-that-does-not-exist.com",
username="admin",
password="admin123"
) as client:
response = client.get("/")
print(f"This shouldn't print: {response}")
except NetworkError as e:
print(f"Network Error: {e.message}")
except Exception as e:
print(f"Other Error: {e}")
def config_based_example():
"""Using configuration-based connection"""
print("\n=== Configuration-Based Example ===")
params = get_connection_params()
print(f"Using config: {params}")
with APIClient(**params) as client:
response = client.get("/")
print(f"Response Status: {response['status']}")
health = client.health_check()
print(f"Health: {health['status']}")
def response_parsing_example():
"""Demonstrate different response types"""
print("\n=== Response Parsing Example ===")
with create_client() as client:
# JSON response (main page)
response = client.get("/")
print(f"Main page type: {type(response['data'])}")
print(f"Main page keys: {list(response['data'].keys()) if isinstance(response['data'], dict) else 'Not a dict'}")
# Text response (health endpoint)
health = client.health_check()
print(f"Health response: {health}")
# Check headers
print(f"Response headers: {response['headers']}")
print(f"Content-Type: {response['headers'].get('Content-Type', 'Unknown')}")
def advanced_usage():
"""Advanced usage with custom parameters"""
print("\n=== Advanced Usage Example ===")
client = APIClient(
base_url="https://airsltd-ocngx.hf.space",
username="admin",
password="admin123",
timeout=10 # Custom timeout
)
try:
# Get with custom parameters (if supported by API)
response = client.get("/", params={"custom": "value"})
print(f"Custom params response: {response['status']}")
# Access response metadata
print(f"Full URL: {response['url']}")
print(f"Status Code: {response['status_code']}")
except Exception as e:
print(f"Error: {e}")
finally:
client.close()
if __name__ == "__main__":
"""Run all examples"""
print("OpenResty API Client Examples")
print("=" * 50)
try:
basic_usage()
convenience_function()
context_manager_example()
error_handling_examples()
config_based_example()
response_parsing_example()
advanced_usage()
except KeyboardInterrupt:
print("\nExamples interrupted by user")
except Exception as e:
print(f"\nUnexpected error in examples: {e}")
print("\n" + "=" * 50)
print("Examples completed!")