Skip to content

PERF: styler uuid control and security #36345

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Sep 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ Performance improvements
- Performance improvement in :meth:`GroupBy.agg` with the ``numba`` engine (:issue:`35759`)
- Performance improvements when creating :meth:`pd.Series.map` from a huge dictionary (:issue:`34717`)
- Performance improvement in :meth:`GroupBy.transform` with the ``numba`` engine (:issue:`36240`)
- ``Styler`` uuid method altered to compress data transmission over web whilst maintaining reasonably low table collision probability (:issue:`36345`)

.. ---------------------------------------------------------------------------

Expand Down
16 changes: 13 additions & 3 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
Tuple,
Union,
)
from uuid import uuid1
from uuid import uuid4

import numpy as np

Expand Down Expand Up @@ -89,6 +89,12 @@ class Styler:

.. versionadded:: 1.0.0

uuid_len : int, default 5
If ``uuid`` is not specified, the length of the ``uuid`` to randomly generate
expressed in hex characters, in range [0, 32].

.. versionadded:: 1.2.0

Attributes
----------
env : Jinja2 jinja2.Environment
Expand Down Expand Up @@ -144,6 +150,7 @@ def __init__(
table_attributes: Optional[str] = None,
cell_ids: bool = True,
na_rep: Optional[str] = None,
uuid_len: int = 5,
):
self.ctx: DefaultDict[Tuple[int, int], List[str]] = defaultdict(list)
self._todo: List[Tuple[Callable, Tuple, Dict]] = []
Expand All @@ -159,7 +166,10 @@ def __init__(
self.index = data.index
self.columns = data.columns

self.uuid = uuid
if not isinstance(uuid_len, int) or not uuid_len >= 0:
raise TypeError("``uuid_len`` must be an integer in range [0, 32].")
self.uuid_len = min(32, uuid_len)
self.uuid = (uuid or uuid4().hex[: self.uuid_len]) + "_"
self.table_styles = table_styles
self.caption = caption
if precision is None:
Expand Down Expand Up @@ -248,7 +258,7 @@ def _translate(self):
precision = self.precision
hidden_index = self.hidden_index
hidden_columns = self.hidden_columns
uuid = self.uuid or str(uuid1()).replace("-", "_")
uuid = self.uuid
ROW_HEADING_CLASS = "row_heading"
COL_HEADING_CLASS = "col_heading"
INDEX_NAME_CLASS = "index_name"
Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/io/formats/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1718,6 +1718,26 @@ def test_colspan_w3(self):
s = Styler(df, uuid="_", cell_ids=False)
assert '<th class="col_heading level0 col0" colspan="2">l0</th>' in s.render()

@pytest.mark.parametrize("len_", [1, 5, 32, 33, 100])
def test_uuid_len(self, len_):
# GH 36345
df = pd.DataFrame(data=[["A"]])
s = Styler(df, uuid_len=len_, cell_ids=False).render()
strt = s.find('id="T_')
end = s[strt + 6 :].find('"')
if len_ > 32:
assert end == 32 + 1
else:
assert end == len_ + 1

@pytest.mark.parametrize("len_", [-2, "bad", None])
def test_uuid_len_raises(self, len_):
# GH 36345
df = pd.DataFrame(data=[["A"]])
msg = "``uuid_len`` must be an integer in range \\[0, 32\\]."
with pytest.raises(TypeError, match=msg):
Styler(df, uuid_len=len_, cell_ids=False).render()


@td.skip_if_no_mpl
class TestStylerMatplotlibDep:
Expand Down