Skip to content
Snippets Groups Projects
Commit 7bbdbdac authored by Jiří Setnička's avatar Jiří Setnička
Browse files

Table: Zavedení in_html a in_export na Column

Pro zjednodušení vyrábění sloupečků a jako příprava na volbu sloupečků
pro export.
parent 1cea1f08
No related branches found
No related tags found
1 merge request!115Výběr sloupečků v exportech
This commit is part of merge request !115. Comments created here will be created in the context of that merge request.
...@@ -4,7 +4,7 @@ from flask import Response, url_for ...@@ -4,7 +4,7 @@ from flask import Response, url_for
from html import escape from html import escape
import io import io
from markupsafe import Markup from markupsafe import Markup
from typing import Any, Dict, Sequence, Optional, Iterable, Union from typing import Any, Dict, List, Sequence, Optional, Iterable, Union
import urllib.parse import urllib.parse
import werkzeug.exceptions import werkzeug.exceptions
...@@ -19,11 +19,15 @@ class Column: ...@@ -19,11 +19,15 @@ class Column:
key: str # Jméno klíče ve slovnících key: str # Jméno klíče ve slovnících
name: str # Název v hlavičce CSV name: str # Název v hlavičce CSV
title: str # Titulek v HTML tabulkách title: str # Titulek v HTML tabulkách
in_html: bool # Jestli sloupec zobrazit na webu
in_export: Optional[bool] # Jestli sloupec defaultně exportovat, None = ani nenabízet
def __init__(self, key: str, name: Optional[str] = None, title: Optional[str] = None): def __init__(self, key: str, name: Optional[str] = None, title: Optional[str] = None, in_html: bool = True, in_export: Optional[bool] = True):
self.key = key self.key = key
self.name = name or key self.name = name or key
self.title = title or self.name self.title = title or self.name
self.in_html = in_html
self.in_export = in_export
class Cell: class Cell:
...@@ -165,6 +169,8 @@ class Table: ...@@ -165,6 +169,8 @@ class Table:
tab = [f'<table class="{self.table_class}" id="{self.id}">', '<thead>', '<tr>'] tab = [f'<table class="{self.table_class}" id="{self.id}">', '<thead>', '<tr>']
for c in self.columns: for c in self.columns:
if not c.in_html:
continue
tab.append(f'\t<th>{c.title}') tab.append(f'\t<th>{c.title}')
tab.append('<tbody>') tab.append('<tbody>')
...@@ -173,6 +179,8 @@ class Table: ...@@ -173,6 +179,8 @@ class Table:
r_attr = [f' {key}="{val}"' for (key, val) in r.html_attr.items()] r_attr = [f' {key}="{val}"' for (key, val) in r.html_attr.items()]
tab.append(f'<tr{"".join(r_attr)}>') tab.append(f'<tr{"".join(r_attr)}>')
for c in self.columns: for c in self.columns:
if not c.in_html:
continue
val = r.get(c.key) val = r.get(c.key)
if isinstance(val, Cell): if isinstance(val, Cell):
tab.append(val.to_html()) tab.append(val.to_html())
...@@ -184,29 +192,29 @@ class Table: ...@@ -184,29 +192,29 @@ class Table:
tab.append("<p>Stáhnout jako <a href='?format=en_csv'>CSV s čárkami</a>, <a href='?format=cs_csv'>CSV se středníky</a> nebo <a href='?format=tsv'>TSV</a>.") tab.append("<p>Stáhnout jako <a href='?format=en_csv'>CSV s čárkami</a>, <a href='?format=cs_csv'>CSV se středníky</a> nebo <a href='?format=tsv'>TSV</a>.")
return Markup("\n".join(tab)) return Markup("\n".join(tab))
def to_csv(self, fmt: FileFormat) -> bytes: def to_csv(self, fmt: FileFormat, export_columns: List[Column]) -> bytes:
out = io.StringIO() out = io.StringIO()
writer = csv.writer(out, dialect=fmt.get_dialect()) writer = csv.writer(out, dialect=fmt.get_dialect())
header = [c.name for c in self.columns] header = [c.name for c in export_columns]
writer.writerow(header) writer.writerow(header)
for row in self.rows: for row in self.rows:
r = [row.get(c.key) for c in self.columns] r = [row.get(c.key) for c in export_columns]
writer.writerow(r) writer.writerow(r)
return out.getvalue().encode(fmt.get_charset()) return out.getvalue().encode(fmt.get_charset())
def to_csv_stream(self, fmt: FileFormat) -> Iterable[bytes]: def to_csv_stream(self, fmt: FileFormat, export_columns: List[Column]) -> Iterable[bytes]:
out = io.StringIO() out = io.StringIO()
writer = csv.writer(out, dialect=fmt.get_dialect()) writer = csv.writer(out, dialect=fmt.get_dialect())
header = [c.name for c in self.columns] header = [c.name for c in export_columns]
writer.writerow(header) writer.writerow(header)
nrows = 0 nrows = 0
for row in self.rows: for row in self.rows:
r = [row.get(c.key) for c in self.columns] r = [row.get(c.key) for c in export_columns]
writer.writerow(r) writer.writerow(r)
nrows += 1 nrows += 1
...@@ -224,10 +232,12 @@ class Table: ...@@ -224,10 +232,12 @@ class Table:
except ValueError: except ValueError:
raise werkzeug.exceptions.NotFound() raise werkzeug.exceptions.NotFound()
export_columns = [c for c in self.columns if c.in_export]
if streaming: if streaming:
resp = Response(self.to_csv_stream(fmt)) resp = Response(self.to_csv_stream(fmt, export_columns))
else: else:
out = self.to_csv(fmt) out = self.to_csv(fmt, export_columns)
resp = app.make_response(out) resp = app.make_response(out)
resp.content_type = fmt.get_content_type() resp.content_type = fmt.get_content_type()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment