askrobots / dbbasic Public

Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.

0 downloads

dbbasic/template_engine.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add DBBasic crate engine logo and update README 0d628db 1 year, 2 months ago History
template_engine.py · 10.9 KB · 314 lines
1#!/usr/bin/env python3
2"""
3DBBasic Template Engine - Clean, Pythonic HTML Generation
4Instead of mixing HTML strings in code, use a component-based approach
5"""
6
7from typing import Dict, List, Any, Optional
8from dataclasses import dataclass
9import json
10
11@dataclass
12class Component:
13 """Base component class for building HTML"""
14 tag: str
15 attrs: Dict[str, str] = None
16 children: List[Any] = None
17 text: str = None
18
19 def render(self) -> str:
20 attrs = self.attrs or {}
21 children = self.children or []
22
23 # Build attributes string
24 attr_str = ' '.join(f'{k}="{v}"' for k, v in attrs.items()) if attrs else ''
25
26 # Self-closing tags
27 if self.tag in ['img', 'input', 'meta', 'link', 'br', 'hr']:
28 return f'<{self.tag} {attr_str}/>'
29
30 # Opening tag
31 html = f'<{self.tag}'
32 if attr_str:
33 html += f' {attr_str}'
34 html += '>'
35
36 # Content
37 if self.text:
38 html += self.text
39 for child in children:
40 if isinstance(child, Component):
41 html += child.render()
42 else:
43 html += str(child)
44
45 # Closing tag
46 html += f'</{self.tag}>'
47 return html
48
49
50class Page:
51 """Page builder using method chaining"""
52 def __init__(self, title: str = "DBBasic"):
53 self.title = title
54 self.components = []
55 self.scripts = []
56 self.styles = []
57
58 def add(self, component):
59 self.components.append(component)
60 return self
61
62 def script(self, content: str):
63 self.scripts.append(content)
64 return self
65
66 def style(self, content: str):
67 self.styles.append(content)
68 return self
69
70 def render(self) -> str:
71 # Build the complete HTML document
72 return f"""<!DOCTYPE html>
73<html lang="en">
74<head>
75 <meta charset="UTF-8">
76 <meta name="viewport" content="width=device-width, initial-scale=1.0">
77 <title>{self.title}</title>
78 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
79 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
80 {''.join(f'<style>{s}</style>' for s in self.styles)}
81</head>
82<body>
83 {''.join(c.render() if isinstance(c, Component) else str(c) for c in self.components)}
84 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
85 {''.join(f'<script>{s}</script>' for s in self.scripts)}
86</body>
87</html>"""
88
89
90# Helper functions for common components
91def div(**attrs):
92 """Create a div component"""
93 children = attrs.pop('children', [])
94 text = attrs.pop('text', None)
95 classes = attrs.pop('classes', [])
96 if classes:
97 attrs['class'] = ' '.join(classes) if isinstance(classes, list) else classes
98 return Component('div', attrs, children, text)
99
100def nav_bar(brand: str, links: List[Dict[str, str]], active: str = None):
101 """Create a Bootstrap navbar"""
102 nav_items = []
103 for link in links:
104 is_active = link.get('name') == active
105 nav_items.append(
106 Component('li', {'class': 'nav-item'}, [
107 Component('a', {
108 'class': f"nav-link {'active' if is_active else ''}",
109 'href': link['url']
110 }, text=link['name'])
111 ])
112 )
113
114 return Component('nav', {'class': 'navbar navbar-expand-lg navbar-light bg-light'}, [
115 div(classes=['container-fluid'], children=[
116 Component('a', {'class': 'navbar-brand', 'href': '#'}, text=brand),
117 Component('ul', {'class': 'navbar-nav ms-auto'}, nav_items)
118 ])
119 ])
120
121def card(title: str, content: str, footer=None, badge=None):
122 """Create a Bootstrap card"""
123 header_children = [Component('h5', {'class': 'card-title'}, text=title)]
124 if badge:
125 header_children.append(Component('span', {'class': f'badge bg-{badge["type"]} ms-2'}, text=badge['text']))
126
127 card_children = [
128 div(classes=['card-body'], children=[
129 div(classes=['d-flex', 'justify-content-between', 'align-items-start'], children=header_children),
130 Component('p', {'class': 'card-text'}, text=content)
131 ])
132 ]
133
134 if footer:
135 card_children.append(
136 div(classes=['card-footer', 'bg-transparent'], children=footer)
137 )
138
139 return div(classes=['card', 'h-100', 'shadow-sm'], children=card_children)
140
141def button(text: str, onclick: str = None, variant: str = 'primary', icon: str = None):
142 """Create a Bootstrap button"""
143 attrs = {'class': f'btn btn-{variant}'}
144 if onclick:
145 attrs['onclick'] = onclick
146
147 children = []
148 if icon:
149 children.append(Component('i', {'class': f'bi bi-{icon} me-2'}))
150 children.append(text)
151
152 return Component('button', attrs, children)
153
154def grid(columns: List[Component], cols_md: int = 3):
155 """Create a responsive grid"""
156 return div(
157 classes=[f'row', 'row-cols-1', f'row-cols-md-{cols_md}', 'g-4'],
158 children=[div(classes=['col'], children=[col]) for col in columns]
159 )
160
161def alert(message: str, alert_type: str = 'info', dismissible: bool = True):
162 """Create a Bootstrap alert"""
163 classes = ['alert', f'alert-{alert_type}']
164 if dismissible:
165 classes.append('alert-dismissible')
166 classes.append('fade')
167 classes.append('show')
168
169 children = [message]
170 if dismissible:
171 children.append(
172 Component('button', {
173 'type': 'button',
174 'class': 'btn-close',
175 'data-bs-dismiss': 'alert'
176 })
177 )
178
179 return div(classes=classes, children=children, role='alert')
180
181
182# Template-specific builders
183class TemplateMarketplace:
184 """Clean template marketplace builder"""
185
186 @staticmethod
187 def build(templates: List[Dict[str, Any]]) -> str:
188 page = Page("Template Marketplace - DBBasic")
189
190 # Add navigation
191 page.add(nav_bar(
192 brand="DBBasic",
193 links=[
194 {'name': 'Monitor', 'url': 'http://localhost:8004'},
195 {'name': 'Data', 'url': 'http://localhost:8005'},
196 {'name': 'AI Services', 'url': 'http://localhost:8003'},
197 {'name': 'Templates', 'url': '/templates'}
198 ],
199 active='Templates'
200 ))
201
202 # Add header
203 page.add(div(classes=['container', 'mt-4'], children=[
204 div(classes=['text-center', 'mb-5'], children=[
205 Component('h1', {'class': 'display-4'}, children=[
206 Component('i', {'class': 'bi bi-shop text-primary me-3'}),
207 'Template Marketplace'
208 ]),
209 Component('p', {'class': 'lead text-muted'},
210 text='Deploy production-ready applications instantly')
211 ]),
212 div(id='alerts')
213 ]))
214
215 # Build template cards
216 cards = []
217 for template in templates:
218 cards.append(card(
219 title=template['name'],
220 content=f"{template['description']} • {template['fields_count']} fields",
221 badge={'text': template['category'], 'type': 'primary'},
222 footer=[
223 button('Preview', f"previewTemplate('{template['id']}')", 'outline-secondary', 'eye'),
224 button('Deploy', f"deployTemplate('{template['id']}')", 'success', 'rocket-takeoff')
225 ]
226 ))
227
228 # Add grid of cards
229 page.add(div(classes=['container'], children=[
230 grid(cards, cols_md=3)
231 ]))
232
233 # Add styles
234 page.style("""
235 .card { transition: transform 0.3s; }
236 .card:hover { transform: translateY(-5px); }
237 .spin { animation: spin 1s linear infinite; }
238 @keyframes spin {
239 from { transform: rotate(0deg); }
240 to { transform: rotate(360deg); }
241 }
242 """)
243
244 # Add scripts
245 page.script("""
246 async function deployTemplate(templateId) {
247 const button = event.target;
248 const originalHTML = button.innerHTML;
249
250 try {
251 button.innerHTML = '<i class="bi bi-arrow-clockwise spin"></i> Deploying...';
252 button.disabled = true;
253
254 const response = await fetch(`/api/templates/deploy?template_id=${encodeURIComponent(templateId)}`, {
255 method: 'POST',
256 headers: { 'Content-Type': 'application/json' },
257 body: JSON.stringify({})
258 });
259
260 const result = await response.json();
261
262 if (response.ok) {
263 button.innerHTML = '<i class="bi bi-check-circle"></i> Deployed!';
264 button.className = 'btn btn-success';
265 showAlert(`Template deployed! <a href="${result.url}" class="alert-link">Open →</a>`, 'success');
266 } else {
267 throw new Error(result.detail || 'Deployment failed');
268 }
269 } catch (error) {
270 button.innerHTML = '<i class="bi bi-x-circle"></i> Failed';
271 button.className = 'btn btn-danger';
272 showAlert(`Error: ${error.message}`, 'danger');
273 } finally {
274 setTimeout(() => {
275 button.innerHTML = originalHTML;
276 button.className = 'btn btn-success';
277 button.disabled = false;
278 }, 3000);
279 }
280 }
281
282 async function previewTemplate(templateId) {
283 try {
284 const response = await fetch(`/api/templates/preview?template_id=${encodeURIComponent(templateId)}`);
285 const result = await response.json();
286
287 if (response.ok) {
288 showAlert(`Preview: ${result.fields_count} fields, ${result.hooks_count} hooks`, 'info');
289 }
290 } catch (error) {
291 showAlert(`Preview failed: ${error.message}`, 'warning');
292 }
293 }
294
295 function showAlert(message, type) {
296 const container = document.getElementById('alerts');
297 const alertEl = document.createElement('div');
298 alertEl.className = `alert alert-${type} alert-dismissible fade show`;
299 alertEl.innerHTML = `
300 ${message}
301 <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
302 `;
303 container.appendChild(alertEl);
304
305 setTimeout(() => {
306 if (alertEl.parentNode) {
307 const bsAlert = new bootstrap.Alert(alertEl);
308 bsAlert.close();
309 }
310 }, 5000);
311 }
312 """)
313
314 return page.render()