Skip to content

Commit

Permalink
base64url encode figure ids
Browse files Browse the repository at this point in the history
  • Loading branch information
oliverlambson committed Aug 26, 2024
1 parent 2c0ef6d commit 58aec49
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
2 changes: 1 addition & 1 deletion bored-charts/boredcharts/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "0.13.0"
__version__ = "0.13.1"

from boredcharts.router import FigureRouter
from boredcharts.webapp import boredcharts
Expand Down
5 changes: 4 additions & 1 deletion bored-charts/boredcharts/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from markupsafe import Markup
from plotly.graph_objects import Figure

from boredcharts.utils import uuid_to_urlid

logger = logging.getLogger("boredcharts")


Expand Down Expand Up @@ -68,7 +70,8 @@ def plotly_to_html(fig: Figure) -> Markup:

def altair_to_html(chart: alt.typing.ChartType) -> Markup:
"""Renders an Altair Chart as HTML."""
figid = f"vis-{uuid.uuid4()}" # html id can't start with digit
id_ = uuid_to_urlid(uuid.uuid4())
figid = f"vis-{id_}" # html id can't start with digit
return Markup(
chart.to_html(
fullhtml=False,
Expand Down
28 changes: 28 additions & 0 deletions bored-charts/boredcharts/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import base64
import uuid
from pathlib import Path
from typing import NamedTuple

Expand Down Expand Up @@ -38,3 +40,29 @@ def to_url_path(path: Path) -> str:
if path.name:
path = path.with_suffix("")
return str(Path("/") / path)


def uuid_to_urlid(uuid_: uuid.UUID) -> str:
"""Convert a UUID to a short URL-safe string.
>>> import base64
>>> import uuid
>>> id_ = uuid.UUID('5d98d578-2731-4a4d-b666-70ca16f10aa2')
>>> url_id = uuid_to_urlid(id_)
>>> print(url_id)
XZjVeCcxSk22ZnDKFvEKog
"""
return base64.urlsafe_b64encode(uuid_.bytes).rstrip(b"=").decode("utf-8")


def urlid_to_uuid(url: str) -> uuid.UUID:
"""Convert a base64url encoded UUID string to a UUID.
>>> import base64
>>> import uuid
>>> url_id = 'XZjVeCcxSk22ZnDKFvEKog'
>>> id_ = urlid_to_uuid(url_id)
>>> print(id_)
5d98d578-2731-4a4d-b666-70ca16f10aa2
"""
return uuid.UUID(bytes=base64.urlsafe_b64decode(url + "=" * (len(url) % 4)))

0 comments on commit 58aec49

Please sign in to comment.