Skip to content

Instantly share code, notes, and snippets.

@tommilligan
Created January 25, 2024 12:40
Show Gist options
  • Select an option

  • Save tommilligan/c2111f944ff496b0b7e87037e103d5a0 to your computer and use it in GitHub Desktop.

Select an option

Save tommilligan/c2111f944ff496b0b7e87037e103d5a0 to your computer and use it in GitHub Desktop.
Request schema enforcement for base64 encoded bytes
def _base64_length(bytes_length: int) -> int:
"""Return the maximum length a base64 encoded string would be for the
given length of bytes.
Note that this length may change if padding is stripped.
"""
# base64 length is 33% longer, rounding up
return ceil((bytes_length / 3) * 4)
def _new_base64_encoded_bytes_regex(max_bytes_length: int) -> Pattern[str]:
"""Returns a regex representing base64 encoding any data up to
max_bytes_length in size.
This pattern excludes padding, as the equals sign is not url safe.
"""
return regex.compile(
r"^[A-Za-z0-9-_]{,%s}\Z" % _base64_length(max_bytes_length)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment