URL manipulation made simple.
65
Create a helper that rewrites URLs into SPA-friendly hashbang fragments while cleaning out unwanted fragment path and query pieces. The helper always works against the fragment portion only; it must not alter the URL's main path or query string.
https://example.com/app with route segments ["dashboard", "stats"] and fragment params { "view": "weekly", "compare": "previous" }, the helper returns https://example.com/app#!dashboard/stats?view=weekly&compare=previous while preserving the provided segment and parameter order. @testhttps://example.com/app#!draft/reports?token=abc&keep=yes&debug=1, dropping the fragment path segment draft and fragment query keys token and debug yields https://example.com/app#!reports?keep=yes; the main URL path/query stay unchanged. @testhttps://example.com/app with route segments ["public", "gallery"] and fragment params { "ref": "share", "page": "2" } produces https://example.com/app#!public/gallery&ref=share&page=2 (no ? between the fragment path and its parameters). @test@generates
from collections.abc import Mapping, Sequence
from typing import Optional
def build_hashbang_url(
base_url: str,
route_segments: Optional[Sequence[str]] = None,
fragment_params: Optional[Mapping[str, str]] = None,
drop_path_segments: Optional[Sequence[str]] = None,
drop_query_keys: Optional[Sequence[str]] = None,
omit_fragment_separator: bool = False,
) -> str:
"""
Returns a URL string whose fragment starts with #!, using the provided route segments and fragment parameters.
- If route_segments is provided, use it as the fragment path; otherwise reuse the existing fragment path from base_url.
- If fragment_params is provided, use it as the fragment query; otherwise reuse existing fragment query values from base_url.
- Remove any fragment path segments matching drop_path_segments and any fragment query keys matching drop_query_keys.
- When omit_fragment_separator is True, do not include a '?' between the fragment path and query parameters.
"""URL builder for composing and cleaning paths, queries, and fragments. @satisfied-by
Install with Tessl CLI
npx tessl i tessl/pypi-furlevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10