From f6c7a9d12f359bf0bb1f204826afc9853042a81b Mon Sep 17 00:00:00 2001 From: Seva Date: Tue, 19 Jan 2021 22:53:07 +0200 Subject: [PATCH] Escape results before output --- datatables/datatables.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/datatables/datatables.py b/datatables/datatables.py index 1d35dcc..49b36c0 100644 --- a/datatables/datatables.py +++ b/datatables/datatables.py @@ -23,7 +23,9 @@ class DataTables: :returns: a DataTables object """ - def __init__(self, request, query, columns, allow_regex_searches=False): + def __init__( + self, request, query, columns, allow_regex_searches=False, escape=None + ): """Initialize object and run the query.""" self.params = dict(request) if "sEcho" in self.params: @@ -33,6 +35,9 @@ def __init__(self, request, query, columns, allow_regex_searches=False): self.results = None self.allow_regex_searches = allow_regex_searches + # callable to escape data + self.escape = escape or self.default_escape + # total in the table after filtering self.cardinality_filtered = 0 @@ -47,6 +52,11 @@ def __init__(self, request, query, columns, allow_regex_searches=False): except Exception as exc: self.error = str(exc) + def default_escape(self, data): + """Escape data before output.""" + # do nothing by default + return data + def output_result(self): """Output results in the format needed by DataTables.""" output = {} @@ -132,7 +142,7 @@ def run(self): col.mData if col.mData else str(i) for i, col in enumerate(self.columns) ] self.results = [ - {k: v for k, v in zip(column_names, row)} for row in query.all() + {k: self.escape(v) for k, v in zip(column_names, row)} for row in query.all() ] def _set_column_filter_expressions(self):