Coverage for fastblocks / adapters / images / cloudflare.py: 28%
152 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Cloudflare Images adapter for FastBlocks."""
3import asyncio
4from contextlib import suppress
5from typing import Any
6from uuid import UUID, uuid4
8import httpx
9from pydantic import SecretStr
11from ._base import ImagesBase, ImagesBaseSettings
14class CloudflareImagesSettings(ImagesBaseSettings):
15 """Settings for Cloudflare Images adapter."""
17 # Required ACB 0.19.0+ metadata
18 MODULE_ID: UUID = UUID("01937d86-5e3b-7f4c-9e8e-a5b6c7d8e9f0") # Static UUID7
19 MODULE_STATUS: str = "stable"
21 # Cloudflare API configuration
22 account_id: str = ""
23 api_token: SecretStr = SecretStr("")
24 delivery_url: str = "" # https://imagedelivery.net/{account_hash}
26 # Image configuration
27 default_variant: str = "public"
28 require_signed_urls: bool = False
29 timeout: int = 30
31 # R2 storage configuration (optional)
32 r2_bucket: str | None = None
33 r2_public_url: str | None = None
36class CloudflareImages(ImagesBase):
37 """Cloudflare Images adapter with R2 storage integration."""
39 # Required ACB 0.19.0+ metadata
40 MODULE_ID: UUID = UUID("01937d86-5e3b-7f4c-9e8e-a5b6c7d8e9f0") # Static UUID7
41 MODULE_STATUS: str = "stable"
43 def __init__(self) -> None:
44 """Initialize Cloudflare Images adapter."""
45 super().__init__()
46 self.settings: CloudflareImagesSettings | None = None
47 self._client: httpx.AsyncClient | None = None
49 # Register with Oneiric resolver (fail gracefully if not supported)
50 with suppress(Exception):
51 depends.set(self)
53 async def _get_client(self) -> httpx.AsyncClient:
54 """Get or create HTTP client."""
55 if not self._client:
56 if not self.settings:
57 self.settings = CloudflareImagesSettings()
59 self._client = httpx.AsyncClient(
60 timeout=self.settings.timeout,
61 headers={
62 "Authorization": f"Bearer {self.settings.api_token.get_secret_value()}",
63 "Content-Type": "application/json",
64 },
65 )
66 return self._client
68 async def upload_image(self, file_data: bytes, filename: str) -> str:
69 """Upload image to Cloudflare Images."""
70 if not self.settings:
71 self.settings = CloudflareImagesSettings()
73 client = await self._get_client()
75 # Generate unique ID for the image
76 str(uuid4())
78 # Prepare upload data
80 # Upload to Cloudflare Images
81 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1"
83 # Format files for httpx - each value is a tuple of (filename, file_content, content_type)
84 files_data: dict[str, tuple[str, bytes, str]] = {
85 "file": (filename, file_data, "image/*"),
86 }
88 response = await client.post(url, files=files_data)
89 response.raise_for_status()
91 result = response.json()
92 if not result.get("success"):
93 raise RuntimeError(
94 f"Upload failed: {result.get('errors', 'Unknown error')}"
95 )
97 # Return the image ID for future reference
98 uploaded_image_id: str = result["result"]["id"]
99 return uploaded_image_id
101 async def get_image_url(
102 self, image_id: str, transformations: dict[str, Any] | None = None
103 ) -> str:
104 """Generate Cloudflare Images URL with transformations."""
105 if not self.settings:
106 self.settings = CloudflareImagesSettings()
108 base_url = self._build_base_url(image_id)
110 if transformations:
111 transform_parts = self._build_transformation_parts(transformations)
112 if transform_parts:
113 return self._build_transformed_url(
114 base_url, transformations, transform_parts
115 )
117 return f"{base_url}/{self.settings.default_variant}"
119 def _build_base_url(self, image_id: str) -> str:
120 """Build base URL for Cloudflare image."""
121 if not self.settings:
122 raise RuntimeError("Cloudflare Images settings not configured")
124 if self.settings.delivery_url:
125 return f"{self.settings.delivery_url}/{image_id}"
126 return f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1/{image_id}"
128 @staticmethod
129 def _build_transformation_parts(transformations: dict[str, Any]) -> list[str]:
130 """Build transformation query parameters."""
131 # Common transformations
132 common_parts = [
133 f"{key}={transformations[key]}"
134 for key in ("width", "height", "quality", "format", "fit")
135 if key in transformations
136 ]
138 # Advanced transformations
139 advanced_parts = [
140 f"{key}={transformations[key]}"
141 for key in ("blur", "brightness", "contrast", "gamma", "sharpen")
142 if key in transformations
143 ]
145 return common_parts + advanced_parts
147 def _build_transformed_url(
148 self, base_url: str, transformations: dict[str, Any], transform_parts: list[str]
149 ) -> str:
150 """Build final URL with transformations."""
151 if not self.settings:
152 raise RuntimeError("Cloudflare Images settings not configured")
154 variant = transformations.get("variant", self.settings.default_variant)
155 transform_string = ",".join(transform_parts)
156 return f"{base_url}/{variant}?{transform_string}"
158 def get_img_tag(self, image_id: str, alt: str, **attributes: Any) -> str:
159 """Generate img tag with Cloudflare Images patterns."""
160 # Generate base URL
161 transformations = attributes.pop("transformations", {})
163 # Use async context for URL generation (in real usage)
164 try:
165 loop = asyncio.get_event_loop()
166 url = loop.run_until_complete(self.get_image_url(image_id, transformations))
167 except RuntimeError:
168 # Create new event loop if none exists
169 loop = asyncio.new_event_loop()
170 asyncio.set_event_loop(loop)
171 url = loop.run_until_complete(self.get_image_url(image_id, transformations))
173 # Build attributes
174 img_attrs = {
175 "src": url,
176 "alt": alt,
177 "loading": "lazy"
178 if self.settings and self.settings.lazy_loading
179 else "eager",
180 } | attributes
182 # Generate tag
183 attr_string = " ".join(
184 f'{k}="{v}"' for k, v in img_attrs.items() if v is not None
185 )
186 return f"<img {attr_string}>"
188 async def delete_image(self, image_id: str) -> bool:
189 """Delete image from Cloudflare Images."""
190 if not self.settings:
191 self.settings = CloudflareImagesSettings()
193 client = await self._get_client()
195 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1/{image_id}"
197 response = await client.delete(url)
198 response.raise_for_status()
200 result = response.json()
201 success: bool = result.get("success", False)
202 return success
204 async def list_images(self, page: int = 1, per_page: int = 50) -> dict[str, Any]:
205 """List images in Cloudflare Images."""
206 if not self.settings:
207 self.settings = CloudflareImagesSettings()
209 client = await self._get_client()
211 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1"
212 params = {"page": page, "per_page": per_page}
214 response = await client.get(url, params=params)
215 response.raise_for_status()
217 result: dict[str, Any] = response.json()
218 return result
220 async def get_usage_stats(self) -> dict[str, Any]:
221 """Get Cloudflare Images usage statistics."""
222 if not self.settings:
223 self.settings = CloudflareImagesSettings()
225 client = await self._get_client()
227 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1/stats"
229 response = await client.get(url)
230 response.raise_for_status()
232 stats: dict[str, Any] = response.json()
233 return stats
235 async def close(self) -> None:
236 """Close HTTP client."""
237 if self._client:
238 await self._client.aclose()
239 self._client = None
242# Template filter registration for FastBlocks
243def register_cloudflare_filters(env: Any) -> None:
244 """Register Cloudflare Images filters for Jinja2 templates."""
246 @env.filter("cf_image_url") # type: ignore[misc]
247 async def cf_image_url_filter(image_id: str, **transformations: Any) -> str:
248 """Template filter for Cloudflare Images URLs."""
249 images = await depends.resolve("fastblocks", "images")
250 if isinstance(images, CloudflareImages):
251 return await images.get_image_url(image_id, transformations)
252 return f"#{image_id}" # Fallback
254 @env.filter("cf_img_tag") # type: ignore[misc]
255 def cf_img_tag_filter(image_id: str, alt: str = "", **attributes: Any) -> str:
256 """Template filter for complete Cloudflare img tags."""
257 images = depends.get_sync("images")
258 if isinstance(images, CloudflareImages):
259 return images.get_img_tag(image_id, alt, **attributes)
260 return f'<img src="#{image_id}" alt="{alt}">' # Fallback
262 @env.global_("cloudflare_responsive_img") # type: ignore[misc]
263 def cloudflare_responsive_img(
264 image_id: str,
265 alt: str,
266 sizes: str = "(max-width: 768px) 100vw, 50vw",
267 **attributes: Any,
268 ) -> str:
269 """Generate responsive image with multiple sizes."""
270 images = depends.get_sync("images")
271 if not isinstance(images, CloudflareImages):
272 return f'<img src="#{image_id}" alt="{alt}">'
274 # Generate srcset for different screen sizes
275 srcset_parts = []
276 widths = [320, 640, 768, 1024, 1280, 1536]
278 for width in widths:
279 try:
280 loop = asyncio.get_event_loop()
281 url = loop.run_until_complete(
282 images.get_image_url(
283 image_id, {"width": width, "fit": "scale-down"}
284 )
285 )
286 srcset_parts.append(f"{url} {width}w")
287 except Exception:
288 continue
290 # Build img tag with srcset
291 base_url = asyncio.get_event_loop().run_until_complete(
292 images.get_image_url(image_id, {"width": 1024, "fit": "scale-down"})
293 )
295 img_attrs = {
296 "src": base_url,
297 "alt": alt,
298 "sizes": sizes,
299 "srcset": ", ".join(srcset_parts),
300 "loading": "lazy",
301 } | attributes
303 attr_string = " ".join(
304 f'{k}="{v}"' for k, v in img_attrs.items() if v is not None
305 )
306 return f"<img {attr_string}>"
309ImagesSettings = CloudflareImagesSettings
310Images = CloudflareImages
313# ACB 0.19.0+ compatibility
314__all__ = [
315 "CloudflareImages",
316 "CloudflareImagesSettings",
317 "register_cloudflare_filters",
318 "Images",
319 "ImagesSettings",
320]