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

1"""Cloudflare Images adapter for FastBlocks.""" 

2 

3import asyncio 

4from contextlib import suppress 

5from typing import Any 

6from uuid import UUID, uuid4 

7 

8import httpx 

9from pydantic import SecretStr 

10 

11from ._base import ImagesBase, ImagesBaseSettings 

12 

13 

14class CloudflareImagesSettings(ImagesBaseSettings): 

15 """Settings for Cloudflare Images adapter.""" 

16 

17 # Required ACB 0.19.0+ metadata 

18 MODULE_ID: UUID = UUID("01937d86-5e3b-7f4c-9e8e-a5b6c7d8e9f0") # Static UUID7 

19 MODULE_STATUS: str = "stable" 

20 

21 # Cloudflare API configuration 

22 account_id: str = "" 

23 api_token: SecretStr = SecretStr("") 

24 delivery_url: str = "" # https://imagedelivery.net/{account_hash} 

25 

26 # Image configuration 

27 default_variant: str = "public" 

28 require_signed_urls: bool = False 

29 timeout: int = 30 

30 

31 # R2 storage configuration (optional) 

32 r2_bucket: str | None = None 

33 r2_public_url: str | None = None 

34 

35 

36class CloudflareImages(ImagesBase): 

37 """Cloudflare Images adapter with R2 storage integration.""" 

38 

39 # Required ACB 0.19.0+ metadata 

40 MODULE_ID: UUID = UUID("01937d86-5e3b-7f4c-9e8e-a5b6c7d8e9f0") # Static UUID7 

41 MODULE_STATUS: str = "stable" 

42 

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 

48 

49 # Register with Oneiric resolver (fail gracefully if not supported) 

50 with suppress(Exception): 

51 depends.set(self) 

52 

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() 

58 

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 

67 

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() 

72 

73 client = await self._get_client() 

74 

75 # Generate unique ID for the image 

76 str(uuid4()) 

77 

78 # Prepare upload data 

79 

80 # Upload to Cloudflare Images 

81 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1" 

82 

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 } 

87 

88 response = await client.post(url, files=files_data) 

89 response.raise_for_status() 

90 

91 result = response.json() 

92 if not result.get("success"): 

93 raise RuntimeError( 

94 f"Upload failed: {result.get('errors', 'Unknown error')}" 

95 ) 

96 

97 # Return the image ID for future reference 

98 uploaded_image_id: str = result["result"]["id"] 

99 return uploaded_image_id 

100 

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() 

107 

108 base_url = self._build_base_url(image_id) 

109 

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 ) 

116 

117 return f"{base_url}/{self.settings.default_variant}" 

118 

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") 

123 

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}" 

127 

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 ] 

137 

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 ] 

144 

145 return common_parts + advanced_parts 

146 

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") 

153 

154 variant = transformations.get("variant", self.settings.default_variant) 

155 transform_string = ",".join(transform_parts) 

156 return f"{base_url}/{variant}?{transform_string}" 

157 

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", {}) 

162 

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)) 

172 

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 

181 

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}>" 

187 

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() 

192 

193 client = await self._get_client() 

194 

195 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1/{image_id}" 

196 

197 response = await client.delete(url) 

198 response.raise_for_status() 

199 

200 result = response.json() 

201 success: bool = result.get("success", False) 

202 return success 

203 

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() 

208 

209 client = await self._get_client() 

210 

211 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1" 

212 params = {"page": page, "per_page": per_page} 

213 

214 response = await client.get(url, params=params) 

215 response.raise_for_status() 

216 

217 result: dict[str, Any] = response.json() 

218 return result 

219 

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() 

224 

225 client = await self._get_client() 

226 

227 url = f"https://api.cloudflare.com/client/v4/accounts/{self.settings.account_id}/images/v1/stats" 

228 

229 response = await client.get(url) 

230 response.raise_for_status() 

231 

232 stats: dict[str, Any] = response.json() 

233 return stats 

234 

235 async def close(self) -> None: 

236 """Close HTTP client.""" 

237 if self._client: 

238 await self._client.aclose() 

239 self._client = None 

240 

241 

242# Template filter registration for FastBlocks 

243def register_cloudflare_filters(env: Any) -> None: 

244 """Register Cloudflare Images filters for Jinja2 templates.""" 

245 

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 

253 

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 

261 

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}">' 

273 

274 # Generate srcset for different screen sizes 

275 srcset_parts = [] 

276 widths = [320, 640, 768, 1024, 1280, 1536] 

277 

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 

289 

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 ) 

294 

295 img_attrs = { 

296 "src": base_url, 

297 "alt": alt, 

298 "sizes": sizes, 

299 "srcset": ", ".join(srcset_parts), 

300 "loading": "lazy", 

301 } | attributes 

302 

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}>" 

307 

308 

309ImagesSettings = CloudflareImagesSettings 

310Images = CloudflareImages 

311 

312 

313# ACB 0.19.0+ compatibility 

314__all__ = [ 

315 "CloudflareImages", 

316 "CloudflareImagesSettings", 

317 "register_cloudflare_filters", 

318 "Images", 

319 "ImagesSettings", 

320]