df2tables 0.3.3__tar.gz → 0.3.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- df2tables-0.3.5/.gitignore +8 -0
- {df2tables-0.3.3 → df2tables-0.3.5}/PKG-INFO +12 -29
- {df2tables-0.3.3 → df2tables-0.3.5}/README.md +10 -6
- {df2tables-0.3.3 → df2tables-0.3.5}/df2tables/__init__.py +1 -1
- df2tables-0.3.5/df2tables/comnt.py +317 -0
- {df2tables-0.3.3 → df2tables-0.3.5}/df2tables/datatable_templ.html +161 -59
- {df2tables-0.3.3 → df2tables-0.3.5}/df2tables/df2tables.py +107 -83
- {df2tables-0.3.3 → df2tables-0.3.5}/df2tables/sample.py +1 -1
- {df2tables-0.3.3 → df2tables-0.3.5}/pyproject.toml +1 -1
- df2tables-0.3.3/LICENSE +0 -21
- df2tables-0.3.3/df2tables/comnt.py +0 -262
|
@@ -1,32 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: df2tables
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.5
|
|
4
4
|
Summary: df2tables: Pandas and Polars DataFrames to Interactive DataTables
|
|
5
5
|
Project-URL: Homepage, https://github.com/ts-kontakt/df2tables
|
|
6
6
|
Project-URL: Issues, https://github.com/ts-kontakt/df2tables/issues
|
|
7
7
|
Author-email: Tomasz Sługocki <ts.kontakt@gmail.com>
|
|
8
|
-
License: MIT
|
|
9
|
-
|
|
10
|
-
Copyright (c) 2024 Tomasz Sługocki
|
|
11
|
-
|
|
12
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
-
in the Software without restriction, including without limitation the rights
|
|
15
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
-
furnished to do so, subject to the following conditions:
|
|
18
|
-
|
|
19
|
-
The above copyright notice and this permission notice shall be included in all
|
|
20
|
-
copies or substantial portions of the Software.
|
|
21
|
-
|
|
22
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
-
SOFTWARE.
|
|
29
|
-
License-File: LICENSE
|
|
8
|
+
License-Expression: MIT
|
|
30
9
|
Keywords: DataTables,HTML,Javascript,Pandas,Polars
|
|
31
10
|
Classifier: Programming Language :: Python :: 3
|
|
32
11
|
Classifier: Programming Language :: Python :: 3.10
|
|
@@ -105,7 +84,7 @@ output_path = df2t.render_sample_df(to_file="sample_table.html")
|
|
|
105
84
|
# Polars sample instead of the pandas default
|
|
106
85
|
output_path = df2t.render_sample_df(df_type="polars", to_file="sample_table_pl.html")
|
|
107
86
|
```
|
|
108
|
-
*The underlying generator, `get_sample_df(df_type="pandas", size=50)`, is also available directly if you just want the sample DataFrame without rendering it.*
|
|
87
|
+
*The underlying generator, `get_sample_df(df_type="pandas", size=50, seed=None)`, is also available directly if you just want the sample DataFrame without rendering it - pass `seed=<int>` for a reproducible frame.*
|
|
109
88
|
|
|
110
89
|
### Rendering in notebook
|
|
111
90
|
```python
|
|
@@ -168,6 +147,8 @@ df2t.render(
|
|
|
168
147
|
- `scroll_x` (bool): Enable horizontal scrolling (default: True)
|
|
169
148
|
- `scroll_y` (str | None): Vertical scrolling height, e.g. `"70vh"`; set to `None` to disable (default: "70vh")
|
|
170
149
|
- `scroll_collapse` (bool): Collapse the container height when there are fewer rows than `scroll_y` (default: True)
|
|
150
|
+
- `list_preview` (int): How many elements of a list/dict cell are shown in its basic preview before the tail is elided (default: 5)
|
|
151
|
+
- `paging_warn_limit` (int | None): Row-count threshold for the in-page performance warning when paging is disabled; `None` keeps the template default (500) (default: None)
|
|
171
152
|
|
|
172
153
|
**Returns:**
|
|
173
154
|
|
|
@@ -307,7 +288,8 @@ The endpoint at `data_url` should return JSON in one of two shapes: a bare array
|
|
|
307
288
|
df2t.to_js_array(
|
|
308
289
|
df: pd.DataFrame | pl.DataFrame,
|
|
309
290
|
precision: int = 2,
|
|
310
|
-
raw: bool = False
|
|
291
|
+
raw: bool = False,
|
|
292
|
+
list_preview: int = 5
|
|
311
293
|
) -> Union[str, list]
|
|
312
294
|
```
|
|
313
295
|
|
|
@@ -317,14 +299,15 @@ Converts a pandas/polars DataFrame to a JavaScript array-of-arrays (strict JSON)
|
|
|
317
299
|
|
|
318
300
|
- `df`: pandas or polars DataFrame
|
|
319
301
|
- `precision`: rounding precision for float columns, same meaning as in `render()` (default: 2)
|
|
320
|
-
- `raw`: if `True`, returns the plain (already
|
|
302
|
+
- `raw`: if `True`, returns the plain (already labelled) Python list of lists instead of a JSON string - convenient for frameworks that JSON-encode the response themselves, e.g. Flask's `jsonify()` (default: False)
|
|
303
|
+
- `list_preview`: how many elements of a list/dict cell are shown in its basic preview (default: 5)
|
|
321
304
|
|
|
322
305
|
**Returns:**
|
|
323
306
|
|
|
324
307
|
- `str`: JSON string like `'[[1,"a",3.5],[2,"b",4.1]]'` (default)
|
|
325
308
|
- `list`: the underlying list of lists, when `raw=True`
|
|
326
309
|
|
|
327
|
-
`NaN
|
|
310
|
+
Missing values of every flavour (`None`, `pd.NA`, `NaT`, ...) carry the single `"NA"` label; non-finite floats keep their names (`"NaN"`, `"inf"`, `"-inf"`). List/dict cells show a bounded basic preview like `'[0, 1, 2, 3, 4, ...]'`. No bare `NaN`/`Infinity` token is ever emitted, so the result always round-trips through `JSON.parse()` / `jsonify()` without error.
|
|
328
311
|
|
|
329
312
|
**Example (Flask):**
|
|
330
313
|
|
|
@@ -352,7 +335,7 @@ except (ValueError, TypeError, FileNotFoundError, RuntimeError, OSError) as e:
|
|
|
352
335
|
print(f"Could not render table: {e}")
|
|
353
336
|
```
|
|
354
337
|
|
|
355
|
-
Only genuinely unknown keyword arguments are non-fatal - they emit a `UserWarning` and are ignored rather than raising.
|
|
338
|
+
Only genuinely unknown keyword arguments are non-fatal - they emit a `UserWarning` and are ignored rather than raising. Unknown `render_opts` keys likewise emit a `UserWarning` and have no effect.
|
|
356
339
|
|
|
357
340
|
### Deprecated Arguments
|
|
358
341
|
|
|
@@ -360,7 +343,7 @@ The following are kept for backward compatibility but will be removed in a futur
|
|
|
360
343
|
|
|
361
344
|
- `load_column_control` and `display_logo` as direct keyword arguments to `render()` / `render_ajax()` - pass them inside `render_opts={...}` instead
|
|
362
345
|
- `num_html` - renamed to `format_negatives`; pass `format_negatives=...` instead
|
|
363
|
-
- `load_datatables()` - a no-op
|
|
346
|
+
- `load_datatables()` - **removed** (it was a no-op and hasn't been needed since v0.1.8); any remaining import of it now fails - just delete it
|
|
364
347
|
|
|
365
348
|
## Configure DataTables directly from Python using `js_opts`
|
|
366
349
|
|
|
@@ -63,7 +63,7 @@ output_path = df2t.render_sample_df(to_file="sample_table.html")
|
|
|
63
63
|
# Polars sample instead of the pandas default
|
|
64
64
|
output_path = df2t.render_sample_df(df_type="polars", to_file="sample_table_pl.html")
|
|
65
65
|
```
|
|
66
|
-
*The underlying generator, `get_sample_df(df_type="pandas", size=50)`, is also available directly if you just want the sample DataFrame without rendering it.*
|
|
66
|
+
*The underlying generator, `get_sample_df(df_type="pandas", size=50, seed=None)`, is also available directly if you just want the sample DataFrame without rendering it - pass `seed=<int>` for a reproducible frame.*
|
|
67
67
|
|
|
68
68
|
### Rendering in notebook
|
|
69
69
|
```python
|
|
@@ -126,6 +126,8 @@ df2t.render(
|
|
|
126
126
|
- `scroll_x` (bool): Enable horizontal scrolling (default: True)
|
|
127
127
|
- `scroll_y` (str | None): Vertical scrolling height, e.g. `"70vh"`; set to `None` to disable (default: "70vh")
|
|
128
128
|
- `scroll_collapse` (bool): Collapse the container height when there are fewer rows than `scroll_y` (default: True)
|
|
129
|
+
- `list_preview` (int): How many elements of a list/dict cell are shown in its basic preview before the tail is elided (default: 5)
|
|
130
|
+
- `paging_warn_limit` (int | None): Row-count threshold for the in-page performance warning when paging is disabled; `None` keeps the template default (500) (default: None)
|
|
129
131
|
|
|
130
132
|
**Returns:**
|
|
131
133
|
|
|
@@ -265,7 +267,8 @@ The endpoint at `data_url` should return JSON in one of two shapes: a bare array
|
|
|
265
267
|
df2t.to_js_array(
|
|
266
268
|
df: pd.DataFrame | pl.DataFrame,
|
|
267
269
|
precision: int = 2,
|
|
268
|
-
raw: bool = False
|
|
270
|
+
raw: bool = False,
|
|
271
|
+
list_preview: int = 5
|
|
269
272
|
) -> Union[str, list]
|
|
270
273
|
```
|
|
271
274
|
|
|
@@ -275,14 +278,15 @@ Converts a pandas/polars DataFrame to a JavaScript array-of-arrays (strict JSON)
|
|
|
275
278
|
|
|
276
279
|
- `df`: pandas or polars DataFrame
|
|
277
280
|
- `precision`: rounding precision for float columns, same meaning as in `render()` (default: 2)
|
|
278
|
-
- `raw`: if `True`, returns the plain (already
|
|
281
|
+
- `raw`: if `True`, returns the plain (already labelled) Python list of lists instead of a JSON string - convenient for frameworks that JSON-encode the response themselves, e.g. Flask's `jsonify()` (default: False)
|
|
282
|
+
- `list_preview`: how many elements of a list/dict cell are shown in its basic preview (default: 5)
|
|
279
283
|
|
|
280
284
|
**Returns:**
|
|
281
285
|
|
|
282
286
|
- `str`: JSON string like `'[[1,"a",3.5],[2,"b",4.1]]'` (default)
|
|
283
287
|
- `list`: the underlying list of lists, when `raw=True`
|
|
284
288
|
|
|
285
|
-
`NaN
|
|
289
|
+
Missing values of every flavour (`None`, `pd.NA`, `NaT`, ...) carry the single `"NA"` label; non-finite floats keep their names (`"NaN"`, `"inf"`, `"-inf"`). List/dict cells show a bounded basic preview like `'[0, 1, 2, 3, 4, ...]'`. No bare `NaN`/`Infinity` token is ever emitted, so the result always round-trips through `JSON.parse()` / `jsonify()` without error.
|
|
286
290
|
|
|
287
291
|
**Example (Flask):**
|
|
288
292
|
|
|
@@ -310,7 +314,7 @@ except (ValueError, TypeError, FileNotFoundError, RuntimeError, OSError) as e:
|
|
|
310
314
|
print(f"Could not render table: {e}")
|
|
311
315
|
```
|
|
312
316
|
|
|
313
|
-
Only genuinely unknown keyword arguments are non-fatal - they emit a `UserWarning` and are ignored rather than raising.
|
|
317
|
+
Only genuinely unknown keyword arguments are non-fatal - they emit a `UserWarning` and are ignored rather than raising. Unknown `render_opts` keys likewise emit a `UserWarning` and have no effect.
|
|
314
318
|
|
|
315
319
|
### Deprecated Arguments
|
|
316
320
|
|
|
@@ -318,7 +322,7 @@ The following are kept for backward compatibility but will be removed in a futur
|
|
|
318
322
|
|
|
319
323
|
- `load_column_control` and `display_logo` as direct keyword arguments to `render()` / `render_ajax()` - pass them inside `render_opts={...}` instead
|
|
320
324
|
- `num_html` - renamed to `format_negatives`; pass `format_negatives=...` instead
|
|
321
|
-
- `load_datatables()` - a no-op
|
|
325
|
+
- `load_datatables()` - **removed** (it was a no-op and hasn't been needed since v0.1.8); any remaining import of it now fails - just delete it
|
|
322
326
|
|
|
323
327
|
## Configure DataTables directly from Python using `js_opts`
|
|
324
328
|
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# coding=utf8
|
|
3
|
+
"""
|
|
4
|
+
Comnt - template content using block-annotated comments
|
|
5
|
+
|
|
6
|
+
Template regions are marked with standard comment syntax, so the template
|
|
7
|
+
stays a valid file you can open in a browser as-is, placeholder included.
|
|
8
|
+
|
|
9
|
+
HTML/XML: <!--[tag_id--> ... <!--tag_id]-->
|
|
10
|
+
JS/CSS: /*[tag_id*/ ... /*tag_id]*/
|
|
11
|
+
|
|
12
|
+
Python values go in as JavaScript source -- no JSON.parse() round trip:
|
|
13
|
+
|
|
14
|
+
const data = /*[data*/ [0, 1] /*data]*/; <- js_value([1, 2, 3])
|
|
15
|
+
|
|
16
|
+
Rules
|
|
17
|
+
- ids are ASCII identifiers: a letter or _ first, then letters, digits
|
|
18
|
+
and _ (the same rule as Python/Jinja2 names, but ASCII only).
|
|
19
|
+
Opening and closing id must match.
|
|
20
|
+
- An id may repeat (same style): render() writes its value into every
|
|
21
|
+
occurrence; get_tag_content(..., occurrence=N) reads one of them.
|
|
22
|
+
- An id uses ONE comment style (use two ids for html and js).
|
|
23
|
+
- Tags may nest. Replacing an outer tag replaces everything inside it,
|
|
24
|
+
so a value given for an inner tag as well is ignored (and reported).
|
|
25
|
+
- A value of None leaves that tag untouched.
|
|
26
|
+
- Markers stay in the output: a rendered file is again a template.
|
|
27
|
+
|
|
28
|
+
Error model
|
|
29
|
+
Problems are detected per id and only matter for ids you actually pass:
|
|
30
|
+
unknown id, id in both comment styles, unbalanced or misordered markers,
|
|
31
|
+
inner tag swallowed by an outer one. A broken id is skipped, never
|
|
32
|
+
guessed. render() then issues one warnings.warn() listing everything;
|
|
33
|
+
strict=True raises a single ValueError instead. get_tag_content()
|
|
34
|
+
raises NotFoundError.
|
|
35
|
+
|
|
36
|
+
Guarantees
|
|
37
|
+
Markers are searched only in the template, in one linear pass, and the
|
|
38
|
+
output is built once, left to right. Values are opaque: marker-like text
|
|
39
|
+
inside a value is copied verbatim and never treated as a tag.
|
|
40
|
+
|
|
41
|
+
Escaping
|
|
42
|
+
Comnt does not escape. Use js_value() for JS (json.dumps plus '<'
|
|
43
|
+
escaping, so '</script>' in data cannot break out of the element) and
|
|
44
|
+
html.escape() for HTML text.
|
|
45
|
+
|
|
46
|
+
Web apps
|
|
47
|
+
render_file() returns a string and caches the scanned template (up to
|
|
48
|
+
16 files, validated by mtime and size, thread-safe), so a large
|
|
49
|
+
template is not rescanned on every request:
|
|
50
|
+
|
|
51
|
+
@app.get("/")
|
|
52
|
+
def index():
|
|
53
|
+
return comnt.render_file("page.html", {"data": comnt.js_value(rows)})
|
|
54
|
+
|
|
55
|
+
Author: Tomasz Slugocki
|
|
56
|
+
Version: 2.0.0
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
import functools
|
|
60
|
+
import json
|
|
61
|
+
import os
|
|
62
|
+
import re
|
|
63
|
+
import secrets
|
|
64
|
+
import stat
|
|
65
|
+
import tempfile
|
|
66
|
+
import warnings
|
|
67
|
+
import webbrowser
|
|
68
|
+
from pathlib import Path
|
|
69
|
+
|
|
70
|
+
__all__ = ['render', 'render_file', 'write_from_template', 'get_tag_content',
|
|
71
|
+
'js_value', 'clear_cache', 'example', 'NotFoundError']
|
|
72
|
+
|
|
73
|
+
__version__ = "2.0.0"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class NotFoundError(ValueError):
|
|
77
|
+
"""A tag is missing, used in both comment styles, or its markers don't
|
|
78
|
+
pair up cleanly. Subclasses ValueError."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_NAME = r'[A-Za-z_][A-Za-z0-9_]*'
|
|
82
|
+
_NAME_RE = re.compile(_NAME)
|
|
83
|
+
|
|
84
|
+
# One pattern for every marker. The name of the group that matched tells
|
|
85
|
+
# which one it was: h/j = html/js comment, o/c = opening/closing marker.
|
|
86
|
+
_MARKER = re.compile(
|
|
87
|
+
r'<!--(?:\[(?P<ho>' + _NAME + r')|(?P<hc>' + _NAME + r')\])-->'
|
|
88
|
+
r'|/\*(?:\[(?P<jo>' + _NAME + r')|(?P<jc>' + _NAME + r')\])\*/'
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _scan(text):
|
|
93
|
+
"""Pair up all markers of `text` in one linear pass.
|
|
94
|
+
|
|
95
|
+
Returns (spans, conflicts, counts):
|
|
96
|
+
spans: {tag_id: [(block_start, body_start, body_end, block_end)]}
|
|
97
|
+
complete pairs in document order; markers of one id are
|
|
98
|
+
paired like brackets, so same-id nesting works
|
|
99
|
+
conflicts: ids that occur in both html and js comments
|
|
100
|
+
counts: {tag_id: (opening, closing)} raw marker counts
|
|
101
|
+
|
|
102
|
+
Never raises; problems are reported only for ids that get used.
|
|
103
|
+
"""
|
|
104
|
+
spans, counts, kinds, stacks, conflicts = {}, {}, {}, {}, set()
|
|
105
|
+
for m in _MARKER.finditer(text):
|
|
106
|
+
group = m.lastgroup
|
|
107
|
+
tag_id = m.group(group)
|
|
108
|
+
kind, is_open = group[0], group[1] == 'o'
|
|
109
|
+
count = counts.setdefault(tag_id, [0, 0])
|
|
110
|
+
count[0 if is_open else 1] += 1
|
|
111
|
+
if kinds.setdefault(tag_id, kind) != kind:
|
|
112
|
+
conflicts.add(tag_id)
|
|
113
|
+
stack = stacks.setdefault(tag_id, [])
|
|
114
|
+
if is_open:
|
|
115
|
+
stack.append((m.start(), m.end()))
|
|
116
|
+
elif stack:
|
|
117
|
+
block_start, body_start = stack.pop()
|
|
118
|
+
spans.setdefault(tag_id, []).append(
|
|
119
|
+
(block_start, body_start, m.start(), m.end()))
|
|
120
|
+
for pairs in spans.values():
|
|
121
|
+
pairs.sort()
|
|
122
|
+
return spans, conflicts, {k: tuple(v) for k, v in counts.items()}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _problem(tag_id, scan):
|
|
126
|
+
"""Why `tag_id` can't be used, or None if it is fine."""
|
|
127
|
+
spans, conflicts, counts = scan
|
|
128
|
+
if tag_id in conflicts:
|
|
129
|
+
return f"'{tag_id}' is used in both html and js comments (use two ids)"
|
|
130
|
+
opening, closing = counts.get(tag_id, (0, 0))
|
|
131
|
+
if not (opening or closing):
|
|
132
|
+
hint = "" if _NAME_RE.fullmatch(tag_id) else \
|
|
133
|
+
" (ids must start with a letter or _ and use only letters, digits and _)"
|
|
134
|
+
return f"'{tag_id}' not found{hint}"
|
|
135
|
+
pairs = len(spans.get(tag_id, ()))
|
|
136
|
+
if pairs != opening or opening != closing:
|
|
137
|
+
return (f"'{tag_id}' has unbalanced or misordered markers "
|
|
138
|
+
f"({opening} opening, {closing} closing, "
|
|
139
|
+
f"{pairs} complete pair(s))")
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _render_scanned(text, repldict, scan, strict):
|
|
144
|
+
"""Substitution over an already scanned template (shared by render()
|
|
145
|
+
and render_file(), so a cached scan can be reused)."""
|
|
146
|
+
spans = scan[0]
|
|
147
|
+
problems, work = [], []
|
|
148
|
+
for tag_id, val in repldict.items():
|
|
149
|
+
if val is None:
|
|
150
|
+
continue
|
|
151
|
+
if not isinstance(val, str):
|
|
152
|
+
raise TypeError(
|
|
153
|
+
f"replacement for '{tag_id}' must be a str or None, "
|
|
154
|
+
f"got {type(val).__name__}")
|
|
155
|
+
problem = _problem(tag_id, scan)
|
|
156
|
+
if problem:
|
|
157
|
+
problems.append(problem)
|
|
158
|
+
else:
|
|
159
|
+
work.extend((*s, tag_id, val) for s in spans[tag_id])
|
|
160
|
+
|
|
161
|
+
work.sort(key=lambda w: w[0]) # outer / leftmost first
|
|
162
|
+
pieces, cursor, owner, ignored = [], 0, None, {}
|
|
163
|
+
for block_start, body_start, body_end, block_end, tag_id, val in work:
|
|
164
|
+
if block_start < cursor: # starts inside a replaced region
|
|
165
|
+
if tag_id != owner: # (an id inside itself is no news)
|
|
166
|
+
key = (tag_id, block_end > cursor) # True: crosses it
|
|
167
|
+
ignored[key] = ignored.get(key, 0) + 1
|
|
168
|
+
continue
|
|
169
|
+
pieces.append(text[cursor:body_start])
|
|
170
|
+
pieces.append(val)
|
|
171
|
+
cursor, owner = body_end, tag_id
|
|
172
|
+
pieces.append(text[cursor:])
|
|
173
|
+
|
|
174
|
+
for (tag_id, crossing), count in ignored.items():
|
|
175
|
+
what = ("crosses another replaced tag (misnested markers)" if crossing
|
|
176
|
+
else "lies inside another replaced tag")
|
|
177
|
+
problems.append(f"'{tag_id}' {what}, its value was ignored in "
|
|
178
|
+
f"{count} of {len(spans[tag_id])} occurrence(s)")
|
|
179
|
+
if problems:
|
|
180
|
+
message = "comnt: " + "; ".join(problems)
|
|
181
|
+
if strict:
|
|
182
|
+
raise ValueError(message)
|
|
183
|
+
warnings.warn(message, stacklevel=3)
|
|
184
|
+
return "".join(pieces)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def render(instr, repldict, strict=False):
|
|
188
|
+
"""Replace the body of each tag named in `repldict` with its value.
|
|
189
|
+
|
|
190
|
+
A repeated id gets the value in every occurrence; None leaves the tag
|
|
191
|
+
untouched. Broken or unknown ids are skipped and reported (see the
|
|
192
|
+
module docstring); strict=True raises ValueError instead.
|
|
193
|
+
"""
|
|
194
|
+
if not isinstance(repldict, dict):
|
|
195
|
+
raise TypeError("repldict must be a dict")
|
|
196
|
+
if not isinstance(instr, str):
|
|
197
|
+
raise TypeError(f"instr must be a str, got {type(instr).__name__}")
|
|
198
|
+
if not repldict:
|
|
199
|
+
return instr
|
|
200
|
+
return _render_scanned(instr, repldict, _scan(instr), strict)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def get_tag_content(tag, instr, occurrence=0):
|
|
204
|
+
"""Return the current content of `tag` without modifying anything.
|
|
205
|
+
`occurrence` (0-based) picks which copy to read if the id repeats."""
|
|
206
|
+
if not isinstance(tag, str) or not tag:
|
|
207
|
+
raise TypeError("'tag' must be a non-empty str")
|
|
208
|
+
if not isinstance(instr, str):
|
|
209
|
+
raise TypeError(f"'instr' must be a str, got {type(instr).__name__}")
|
|
210
|
+
scan = _scan(instr)
|
|
211
|
+
problem = _problem(tag, scan)
|
|
212
|
+
if problem:
|
|
213
|
+
raise NotFoundError(problem)
|
|
214
|
+
pairs = scan[0][tag]
|
|
215
|
+
if not 0 <= occurrence < len(pairs):
|
|
216
|
+
raise IndexError(
|
|
217
|
+
f"tag '{tag}' has {len(pairs)} occurrence(s); "
|
|
218
|
+
f"requested occurrence index {occurrence}")
|
|
219
|
+
_, body_start, body_end, _ = pairs[occurrence]
|
|
220
|
+
return instr[body_start:body_end]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def js_value(obj):
|
|
224
|
+
"""Python object -> JavaScript literal that is safe inside <script>."""
|
|
225
|
+
return json.dumps(obj).replace("<", "\\u003c")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _normpath(path):
|
|
229
|
+
return os.path.normcase(os.path.realpath(path))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@functools.lru_cache(maxsize=16)
|
|
233
|
+
def _load(path, mtime_ns, size):
|
|
234
|
+
# mtime and size are not used in the body: they are part of the cache
|
|
235
|
+
# key, so an edited file is simply a cache miss.
|
|
236
|
+
with open(path, encoding="utf-8", newline="") as op_file:
|
|
237
|
+
text = op_file.read()
|
|
238
|
+
return text, _scan(text)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def clear_cache():
|
|
242
|
+
"""Forget all cached templates (mostly useful in tests)."""
|
|
243
|
+
_load.cache_clear()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def render_file(template, repldict, strict=False):
|
|
247
|
+
"""render() for a template file, returning a str. The text and its scan
|
|
248
|
+
are cached until the file's mtime or size changes."""
|
|
249
|
+
if not isinstance(repldict, dict):
|
|
250
|
+
raise TypeError("repldict must be a dict")
|
|
251
|
+
path = os.path.abspath(template)
|
|
252
|
+
st = os.stat(path)
|
|
253
|
+
text, scan = _load(path, st.st_mtime_ns, st.st_size)
|
|
254
|
+
return _render_scanned(text, repldict, scan, strict)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def write_from_template(template, newfile, repldict, strict=False):
|
|
258
|
+
"""Render the file `template` and write the result to `newfile`.
|
|
259
|
+
Written atomically (temp file + os.replace), so a crash can never leave
|
|
260
|
+
a half-written file. newline="" keeps the original line endings.
|
|
261
|
+
A new file gets the usual umask-based permissions; an existing `newfile`
|
|
262
|
+
keeps its permissions."""
|
|
263
|
+
newfile = os.fspath(newfile)
|
|
264
|
+
if _normpath(template) == _normpath(newfile):
|
|
265
|
+
raise ValueError("template and newfile must be different paths")
|
|
266
|
+
replaced = render_file(template, repldict, strict)
|
|
267
|
+
try:
|
|
268
|
+
mode = stat.S_IMODE(os.stat(newfile).st_mode)
|
|
269
|
+
except FileNotFoundError:
|
|
270
|
+
mode = None
|
|
271
|
+
tmp = f"{newfile}.{secrets.token_hex(4)}.tmp"
|
|
272
|
+
try:
|
|
273
|
+
with open(tmp, "x", encoding="utf-8", newline="") as outfile:
|
|
274
|
+
if mode is not None:
|
|
275
|
+
os.chmod(tmp, mode) # before any data is written
|
|
276
|
+
outfile.write(replaced)
|
|
277
|
+
os.replace(tmp, newfile)
|
|
278
|
+
except BaseException:
|
|
279
|
+
try:
|
|
280
|
+
os.unlink(tmp)
|
|
281
|
+
except OSError:
|
|
282
|
+
pass
|
|
283
|
+
raise
|
|
284
|
+
return True
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def example():
|
|
288
|
+
"""Render a small demo page and open it in the default browser."""
|
|
289
|
+
template = """<!DOCTYPE html>
|
|
290
|
+
<html>
|
|
291
|
+
<head><meta charset="utf-8"><title>comnt example</title></head>
|
|
292
|
+
<body>
|
|
293
|
+
<h1><!--[title-->Welcome to our site!<!--title]--></h1>
|
|
294
|
+
<!--[content--><p>This is placeholder content.</p><!--content]-->
|
|
295
|
+
<pre id="out"></pre>
|
|
296
|
+
<p><small><!--[title-->Welcome to our site!<!--title]--></small></p>
|
|
297
|
+
<script>
|
|
298
|
+
// A Python dict, injected as a JS value
|
|
299
|
+
const data = /*[data*/ {"name": "Ada"} /*data]*/;
|
|
300
|
+
document.getElementById("out").textContent = JSON.stringify(data, null, 2);
|
|
301
|
+
</script>
|
|
302
|
+
</body>
|
|
303
|
+
</html>
|
|
304
|
+
"""
|
|
305
|
+
page = render(template, {
|
|
306
|
+
"title": "Example rendered from Python",
|
|
307
|
+
"content": "<p>Below: a Python dict rendered as a JavaScript object.</p>",
|
|
308
|
+
"data": js_value({"name": "Ada", "age": 37, "roles": ["admin", "editor"]}),
|
|
309
|
+
})
|
|
310
|
+
path = os.path.join(tempfile.gettempdir(), "comnt_example.html")
|
|
311
|
+
with open(path, "w", encoding="utf-8") as outfile:
|
|
312
|
+
outfile.write(page)
|
|
313
|
+
webbrowser.open(Path(path).as_uri())
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
if __name__ == "__main__":
|
|
317
|
+
example()
|