Coverage for fastblocks / adapters / routes / default.py: 36%

137 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Default Routes Adapter for FastBlocks. 

2 

3Provides dynamic route discovery and registration for FastBlocks applications. 

4Includes automatic route gathering from adapters, static file serving, and HTMX endpoint support. 

5 

6Features: 

7- Dynamic route discovery from adapter modules 

8- HTMX-aware endpoints with template fragment rendering 

9- Built-in static routes (favicon, robots.txt) 

10- Automatic static file serving for storage adapters 

11- Template block rendering endpoints 

12- Route gathering from base routes.py files 

13- Integration with FastBlocks template system 

14 

15Requirements: 

16- starlette>=0.47.1 

17- jinja2>=3.1.6 

18 

19Usage: 

20```python 

21# Oneiric imports - ACB imports removed 

22# routes = depends.resolve("fastblocks", "routes") 

23# Routes = import_adapter("routes") 

24# app_routes = routes.routes 

25``` 

26 

27Author: lesleslie <les@wedgwoodwebworks.com> 

28Created: 2025-01-12 

29""" 

30 

31import typing as t 

32from contextlib import suppress 

33from importlib import import_module 

34from uuid import UUID 

35 

36from anyio import Path as AsyncPath 

37from jinja2.exceptions import TemplateNotFound 

38 

39# Oneiric imports 

40from oneiric.core.resolution import Resolver 

41from starlette.endpoints import HTTPEndpoint 

42from starlette.exceptions import HTTPException 

43from starlette.requests import Request 

44from starlette.responses import PlainTextResponse, Response 

45from starlette.routing import Host, Mount, Route, Router, WebSocketRoute 

46from starlette.types import Receive, Scope, Send 

47from fastblocks.actions.query import create_query_context 

48from fastblocks.htmx import HtmxRequest 

49 

50 

51# Custom implementations for ACB compatibility 

52def debug(msg: str) -> None: 

53 """Custom debug function for Oneiric compatibility.""" 

54 print(f"[DEBUG] {msg}") 

55 

56 

57class AdapterStatus: 

58 """Custom AdapterStatus for Oneiric compatibility.""" 

59 

60 STABLE = "STABLE" 

61 BETA = "BETA" 

62 ALPHA = "ALPHA" 

63 EXPERIMENTAL = "EXPERIMENTAL" 

64 

65 

66def root_path(): 

67 """Custom implementation for Oneiric compatibility.""" 

68 return "/" 

69 

70 

71# Oneiric resolver for dependency injection 

72depends = Resolver() 

73 

74from ._base import RoutesBase, RoutesBaseSettings 

75 

76# Placeholder for templates (will be resolved via Oneiric) 

77Templates = None 

78 

79base_routes_path = AsyncPath(root_path()) / "routes.py" 

80 

81 

82class RoutesSettings(RoutesBaseSettings): 

83 """Routes settings using OneiricSettings.""" 

84 

85 def __init__(self, **data: dict) -> None: 

86 super().__init__(**data) 

87 

88 

89class FastBlocksEndpoint(HTTPEndpoint): 

90 def __init__( 

91 self, 

92 scope: Scope, 

93 receive: Receive, 

94 send: Send, 

95 config: t.Any | None = None, 

96 ) -> None: 

97 super().__init__(scope, receive, send) 

98 self.config = config 

99 # Resolve templates via Oneiric resolver (fail gracefully) 

100 with suppress(Exception): 

101 self.templates = depends.resolve("templates") 

102 

103 

104class Index(FastBlocksEndpoint): 

105 async def get(self, request: HtmxRequest | Request) -> Response: 

106 debug(request) 

107 path_params = getattr(request, "path_params", {}) 

108 page = path_params.get("page") or "home" 

109 template = "index.html" 

110 headers = {"vary": "hx-request"} 

111 scope = getattr(request, "scope", {}) 

112 if htmx := scope.get("htmx"): 

113 debug(htmx) 

114 template = f"{page.lstrip('/')}.html" 

115 headers["hx-push-url"] = "/" if page == "home" else page 

116 debug(page, template) 

117 context = await create_query_context( 

118 request, base_context={"page": page.lstrip("/")} 

119 ) 

120 query_params = getattr(request, "query_params", {}) 

121 if "model" in query_params: 

122 model_name = query_params["model"] 

123 if f"{model_name}_parser" in context: 

124 parser = context[f"{model_name}_parser"] 

125 context[f"{model_name}_list"] = await parser.parse_and_execute() 

126 context[f"{model_name}_count"] = await parser.get_count() 

127 try: 

128 result = await self.templates.render_template( 

129 request, 

130 template, 

131 headers=headers, 

132 context=context, 

133 ) 

134 return t.cast(Response, result) 

135 except TemplateNotFound: 

136 raise HTTPException(status_code=404) 

137 

138 

139class Block(FastBlocksEndpoint): 

140 async def get(self, request: HtmxRequest | Request) -> Response: 

141 debug(request) 

142 path_params = getattr(request, "path_params", {}) 

143 block = f"blocks/{path_params.get('block', 'default')}.html" 

144 context = await create_query_context(request) 

145 query_params = getattr(request, "query_params", {}) 

146 if "model" in query_params: 

147 model_name = query_params["model"] 

148 if f"{model_name}_parser" in context: 

149 parser = context[f"{model_name}_parser"] 

150 context[f"{model_name}_list"] = await parser.parse_and_execute() 

151 context[f"{model_name}_count"] = await parser.get_count() 

152 try: 

153 result = await self.templates.render_template( 

154 request, block, context=context 

155 ) 

156 return t.cast(Response, result) 

157 except TemplateNotFound: 

158 raise HTTPException(status_code=404) 

159 

160 

161class Component(FastBlocksEndpoint): 

162 async def get(self, request: HtmxRequest | Request) -> Response: 

163 debug(request) 

164 component_name = getattr(request, "path_params", {}).get("component", "default") 

165 query_params = getattr(request, "query_params", {}) 

166 context = await create_query_context(request, base_context=dict(query_params)) 

167 if "model" in query_params: 

168 model_name = query_params["model"] 

169 if f"{model_name}_parser" in context: 

170 parser = context[f"{model_name}_parser"] 

171 context[f"{model_name}_list"] = await parser.parse_and_execute() 

172 context[f"{model_name}_count"] = await parser.get_count() 

173 try: 

174 htmy = await depends.resolve("fastblocks", "htmy") 

175 if htmy is None: 

176 raise HTTPException( 

177 status_code=500, detail="HTMY adapter not available" 

178 ) 

179 result = await htmy.render_component( 

180 request, component_name, context=context 

181 ) 

182 return t.cast(Response, result) 

183 except Exception as e: 

184 debug(f"Component '{component_name}' not found: {e}") 

185 raise HTTPException(status_code=404) 

186 

187 

188class Routes(RoutesBase): 

189 routes: list[Route | Router | Mount | Host | WebSocketRoute] = [] 

190 

191 async def gather_routes(self, path: AsyncPath) -> None: 

192 depth = -2 

193 if "adapters" in path.parts: 

194 depth = -4 

195 module_path = ".".join(path.parts[depth:]).removesuffix(".py") 

196 debug(path, depth, module_path) 

197 with suppress(ModuleNotFoundError): 

198 module = import_module(module_path) 

199 module_routes = getattr(module, "routes", None) 

200 if module_routes and isinstance(module_routes, list): 

201 self.routes = module.routes + self.routes 

202 

203 @staticmethod 

204 async def favicon(request: Request) -> Response: 

205 return PlainTextResponse("", 200) 

206 

207 @staticmethod 

208 async def robots(request: Request) -> Response: 

209 txt = "User-agent: *\nDisallow: /dashboard/\nDisallow: /blocks/" 

210 return PlainTextResponse(txt, 200) 

211 

212 async def init(self) -> None: 

213 self.routes.extend( 

214 [ 

215 Route("/favicon.ico", endpoint=self.favicon, methods=["GET"]), 

216 Route("/robots.txt", endpoint=self.robots, methods=["GET"]), 

217 Route("/", Index, methods=["GET"]), 

218 Route("/{page}", Index, methods=["GET"]), 

219 Route("/block/{block}", Block, methods=["GET"]), 

220 Route("/component/{component}", Component, methods=["GET"]), 

221 ], 

222 ) 

223 # For Oneiric, we'll use a simpler approach 

224 # In practice, this would be replaced with actual adapter discovery 

225 if await base_routes_path.exists(): 

226 await self.gather_routes(base_routes_path) 

227 # Static file serving (simplified for Oneiric) 

228 with suppress(Exception): 

229 from starlette.staticfiles import StaticFiles 

230 

231 # Placeholder for storage path (would be resolved via Oneiric) 

232 storage_path = AsyncPath("/tmp") / "media" 

233 self.routes.append( 

234 Mount( 

235 "/media", 

236 app=StaticFiles(directory=storage_path), 

237 name="media", 

238 ), 

239 ) 

240 # Development static files 

241 static_path = AsyncPath("/tmp") / "static" 

242 self.routes.append( 

243 Mount( 

244 "/static", 

245 app=StaticFiles(directory=static_path), 

246 name="static", 

247 ), 

248 ) 

249 debug(self.routes) 

250 

251 

252MODULE_ID = UUID("01937d86-6f4c-7d5e-a01f-3456789012cd") 

253MODULE_STATUS = AdapterStatus.STABLE 

254 

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

256with suppress(Exception): 

257 depends.set(Routes, "default")