コンテンツにスキップ

pytilpack.base64

pytilpack.base64

Base64エンコーディング/デコーディングユーティリティ。

encode(s, url_safe=False)

文字列またはバイト列をBase64エンコードする。

文字列が与えられた場合はUTF-8としてエンコードする。

引数:

名前 タイプ デスクリプション デフォルト
s str | bytes

エンコードする文字列またはバイト列。

必須
url_safe bool

URLセーフなBase64エンコードを使用するかどうか。

False

戻り値:

タイプ デスクリプション
str

Base64エンコードされた文字列。

ソースコード位置: pytilpack/base64.py
def encode(s: str | bytes, url_safe: bool = False) -> str:
    """文字列またはバイト列をBase64エンコードする。

    文字列が与えられた場合はUTF-8としてエンコードする。

    Args:
        s: エンコードする文字列またはバイト列。
        url_safe: URLセーフなBase64エンコードを使用するかどうか。

    Returns:
        Base64エンコードされた文字列。
    """
    b = s.encode("utf-8") if isinstance(s, str) else s
    encoded = base64.urlsafe_b64encode(b) if url_safe else base64.b64encode(b)
    return encoded.decode("ascii")

decode(s, url_safe=False)

Base64エンコードされた文字列をデコードする。

引数:

名前 タイプ デスクリプション デフォルト
s str

Base64エンコードされた文字列。

必須
url_safe bool

URLセーフなBase64エンコードを使用しているかどうか。

False

戻り値:

タイプ デスクリプション
bytes

デコードされたバイト列。

ソースコード位置: pytilpack/base64.py
def decode(s: str, url_safe: bool = False) -> bytes:
    """Base64エンコードされた文字列をデコードする。

    Args:
        s: Base64エンコードされた文字列。
        url_safe: URLセーフなBase64エンコードを使用しているかどうか。

    Returns:
        デコードされたバイト列。
    """
    return base64.urlsafe_b64decode(s) if url_safe else base64.b64decode(s)