Spaces:
Paused
Paused
File size: 7,550 Bytes
d94d354 |
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 229 |
"""
Cloudflare API Client
Handles authentication and base HTTP operations for Cloudflare services
"""
import asyncio
import json
from typing import Any, Dict, Optional, Union
import aiohttp
from app.logger import logger
class CloudflareClient:
"""Base client for Cloudflare API operations"""
def __init__(
self,
api_token: str,
account_id: str,
worker_url: Optional[str] = None,
timeout: int = 30,
):
self.api_token = api_token
self.account_id = account_id
self.worker_url = worker_url
self.timeout = timeout
self.base_url = "https://api.cloudflare.com/client/v4"
# HTTP headers for API requests
self.headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
async def _make_request(
self,
method: str,
url: str,
data: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
use_worker: bool = False,
) -> Dict[str, Any]:
"""Make HTTP request to Cloudflare API or Worker"""
# Use worker URL if specified and use_worker is True
if use_worker and self.worker_url:
full_url = f"{self.worker_url.rstrip('/')}/{url.lstrip('/')}"
else:
full_url = f"{self.base_url}/{url.lstrip('/')}"
request_headers = self.headers.copy()
if headers:
request_headers.update(headers)
timeout = aiohttp.ClientTimeout(total=self.timeout)
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.request(
method=method.upper(),
url=full_url,
headers=request_headers,
json=data if data else None,
) as response:
response_text = await response.text()
try:
response_data = (
json.loads(response_text) if response_text else {}
)
except json.JSONDecodeError:
response_data = {"raw_response": response_text}
if not response.ok:
logger.error(
f"Cloudflare API error: {response.status} - {response_text}"
)
raise CloudflareError(
f"HTTP {response.status}: {response_text}",
response.status,
response_data,
)
return response_data
except asyncio.TimeoutError:
logger.error(f"Timeout making request to {full_url}")
raise CloudflareError(f"Request timeout after {self.timeout}s")
except aiohttp.ClientError as e:
logger.error(f"HTTP client error: {e}")
raise CloudflareError(f"Client error: {e}")
async def get(
self,
url: str,
headers: Optional[Dict[str, str]] = None,
use_worker: bool = False,
) -> Dict[str, Any]:
"""Make GET request"""
return await self._make_request(
"GET", url, headers=headers, use_worker=use_worker
)
async def post(
self,
url: str,
data: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
use_worker: bool = False,
) -> Dict[str, Any]:
"""Make POST request"""
return await self._make_request(
"POST", url, data=data, headers=headers, use_worker=use_worker
)
async def put(
self,
url: str,
data: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
use_worker: bool = False,
) -> Dict[str, Any]:
"""Make PUT request"""
return await self._make_request(
"PUT", url, data=data, headers=headers, use_worker=use_worker
)
async def delete(
self,
url: str,
headers: Optional[Dict[str, str]] = None,
use_worker: bool = False,
) -> Dict[str, Any]:
"""Make DELETE request"""
return await self._make_request(
"DELETE", url, headers=headers, use_worker=use_worker
)
async def upload_file(
self,
url: str,
file_data: bytes,
content_type: str = "application/octet-stream",
headers: Optional[Dict[str, str]] = None,
use_worker: bool = False,
) -> Dict[str, Any]:
"""Upload file data"""
# Use worker URL if specified and use_worker is True
if use_worker and self.worker_url:
full_url = f"{self.worker_url.rstrip('/')}/{url.lstrip('/')}"
else:
full_url = f"{self.base_url}/{url.lstrip('/')}"
upload_headers = {
"Authorization": f"Bearer {self.api_token}",
"Content-Type": content_type,
}
if headers:
upload_headers.update(headers)
timeout = aiohttp.ClientTimeout(
total=self.timeout * 2
) # Longer timeout for uploads
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.put(
url=full_url, headers=upload_headers, data=file_data
) as response:
response_text = await response.text()
try:
response_data = (
json.loads(response_text) if response_text else {}
)
except json.JSONDecodeError:
response_data = {"raw_response": response_text}
if not response.ok:
logger.error(
f"File upload error: {response.status} - {response_text}"
)
raise CloudflareError(
f"Upload failed: HTTP {response.status}",
response.status,
response_data,
)
return response_data
except asyncio.TimeoutError:
logger.error(f"Timeout uploading file to {full_url}")
raise CloudflareError(f"Upload timeout after {self.timeout * 2}s")
except aiohttp.ClientError as e:
logger.error(f"Upload client error: {e}")
raise CloudflareError(f"Upload error: {e}")
def get_account_url(self, endpoint: str) -> str:
"""Get URL for account-scoped endpoint"""
return f"accounts/{self.account_id}/{endpoint}"
def get_worker_url(self, endpoint: str) -> str:
"""Get URL for worker endpoint"""
if not self.worker_url:
raise CloudflareError("Worker URL not configured")
return endpoint
class CloudflareError(Exception):
"""Cloudflare API error"""
def __init__(
self,
message: str,
status_code: Optional[int] = None,
response_data: Optional[Dict[str, Any]] = None,
):
super().__init__(message)
self.status_code = status_code
self.response_data = response_data or {}
def __str__(self) -> str:
if self.status_code:
return f"CloudflareError({self.status_code}): {super().__str__()}"
return f"CloudflareError: {super().__str__()}"
|