Spaces:
Sleeping
Sleeping
File size: 7,621 Bytes
0021b08 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | #!/usr/bin/env python3
"""
Example usage scripts for the WebSocket Processing Client
This file contains example functions showing different ways to use the client.
You can run these examples or use them as templates for your own scripts.
"""
import asyncio
import sys
import os
# Add the current directory to Python path to import our client
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from client import ProcessingClient
async def example_simple_request():
"""Example 1: Simple single request"""
print("πΉ Example 1: Simple Single Request")
print("=" * 50)
client = ProcessingClient()
if await client.connect():
request_id = await client.send_processing_request(
foldername="customer-data-2025",
environment="production"
)
await client.disconnect()
if request_id:
print(f"β
Request completed with ID: {request_id}")
else:
print("β Request failed")
print("\n")
async def example_multiple_requests():
"""Example 2: Multiple sequential requests"""
print("πΉ Example 2: Multiple Sequential Requests")
print("=" * 50)
requests = [
{"foldername": "sales-data-q1", "environment": "staging"},
{"foldername": "sales-data-q2", "environment": "staging"},
{"foldername": "sales-data-q3", "environment": "staging"},
]
client = ProcessingClient()
if await client.connect():
for i, req in enumerate(requests, 1):
print(f"\nπ€ Processing request {i}/{len(requests)}")
request_id = await client.send_processing_request(
foldername=req["foldername"],
environment=req["environment"]
)
if request_id:
print(f"β
Request {i} completed: {request_id}")
else:
print(f"β Request {i} failed")
await client.disconnect()
print("\n")
async def example_concurrent_requests():
"""Example 3: Concurrent requests to different servers/endpoints"""
print("πΉ Example 3: Concurrent Requests")
print("=" * 50)
async def process_request(client_id: int, foldername: str, environment: str):
client = ProcessingClient()
if await client.connect():
print(f"π Client {client_id}: Starting request for {foldername}")
request_id = await client.send_processing_request(foldername, environment)
await client.disconnect()
if request_id:
print(f"β
Client {client_id}: Completed with ID {request_id}")
return True
else:
print(f"β Client {client_id}: Failed")
return False
return False
# Run 3 concurrent requests
tasks = [
process_request(1, "dataset-alpha", "development"),
process_request(2, "dataset-beta", "staging"),
process_request(3, "dataset-gamma", "production"),
]
results = await asyncio.gather(*tasks)
successful = sum(results)
print(f"\nπ Completed: {successful}/{len(tasks)} requests successful")
print("\n")
async def example_custom_server():
"""Example 4: Connect to custom server URL"""
print("πΉ Example 4: Custom Server Connection")
print("=" * 50)
# Example with different server (you would change this to your actual server)
custom_url = "ws://10.170.2.156:8000/ws" # Change this to test different servers
client = ProcessingClient(url=custom_url)
print(f"π Connecting to custom server: {custom_url}")
if await client.connect():
request_id = await client.send_processing_request(
foldername="remote-processing-test",
environment="custom-env"
)
await client.disconnect()
if request_id:
print(f"β
Custom server request completed: {request_id}")
else:
print("β Custom server request failed")
else:
print("β Failed to connect to custom server")
print("\n")
async def example_error_handling():
"""Example 5: Error handling and invalid requests"""
print("πΉ Example 5: Error Handling")
print("=" * 50)
client = ProcessingClient()
if await client.connect():
# This should work
print("π€ Sending valid request...")
request_id = await client.send_processing_request(
foldername="valid-folder",
environment="development"
)
if request_id:
print(f"β
Valid request completed: {request_id}")
# Test with empty values (will be handled by the client validation)
print("\nπ€ Testing with empty folder name...")
try:
# The server will handle this validation
await client.websocket.send('{"foldername": "", "environment": "test"}')
# Listen for error response
message = await client.websocket.recv()
data = asyncio.create_task(asyncio.sleep(0)) # Quick way to parse JSON
print(f"π¨ Server response: {message}")
except Exception as e:
print(f"β οΈ Caught error: {e}")
await client.disconnect()
print("\n")
async def run_all_examples():
"""Run all examples in sequence"""
print("π Running All Client Examples")
print("=" * 60)
print()
examples = [
example_simple_request,
example_multiple_requests,
example_concurrent_requests,
example_custom_server,
example_error_handling,
]
for example in examples:
try:
await example()
await asyncio.sleep(1) # Brief pause between examples
except KeyboardInterrupt:
print("\nβΉοΈ Examples interrupted by user")
break
except Exception as e:
print(f"β Error in example: {e}")
continue
print("β
All examples completed!")
def main():
"""Main function to run examples"""
if len(sys.argv) > 1:
example_name = sys.argv[1].lower()
examples_map = {
"simple": example_simple_request,
"multiple": example_multiple_requests,
"concurrent": example_concurrent_requests,
"custom": example_custom_server,
"error": example_error_handling,
"all": run_all_examples,
}
if example_name in examples_map:
print(f"Running example: {example_name}")
asyncio.run(examples_map[example_name]())
else:
print(f"β Unknown example: {example_name}")
print(f"Available examples: {', '.join(examples_map.keys())}")
else:
print("π WebSocket Client Examples")
print("=" * 30)
print()
print("Usage:")
print(" python examples.py simple # Run simple request example")
print(" python examples.py multiple # Run multiple requests example")
print(" python examples.py concurrent # Run concurrent requests example")
print(" python examples.py custom # Run custom server example")
print(" python examples.py error # Run error handling example")
print(" python examples.py all # Run all examples")
print()
print("Or run without arguments to see this help.")
if __name__ == "__main__":
main() |