Skip to content

Models

Attachment

Bases: Struct

Represents an attachment with its content and name.

name instance-attribute

name: str

The name of the attachment.

content instance-attribute

content: bytes

The binary content of the attachment.

from_file classmethod

from_file(
    file: str | PathLike[str], *, name: str | None = None
) -> Self

Create an Attachment instance from a file path.

If a name is not provided, the filename from the path is used as the attachment name.

Parameters:

Name Type Description Default
file str | PathLike[str]

Path to the file from which to create the attachment.

required
name str | None

The desired name for the attachment. If None, the filename from file is used.

None

Returns:

Type Description
Self

Raises:

Type Description
FileNotFoundError

If the provided file path does not exist or is not a file.

Source code in src/privatebin/_models.py
@classmethod
def from_file(cls, file: str | PathLike[str], *, name: str | None = None) -> Self:
    """
    Create an `Attachment` instance from a file path.

    If a name is not provided, the filename from the path is used as the attachment name.

    Parameters
    ----------
    file : str | PathLike[str]
        Path to the file from which to create the attachment.
    name : str | None, optional
        The desired name for the attachment. If `None`, the filename from `file` is used.

    Returns
    -------
    Self

    Raises
    ------
    FileNotFoundError
        If the provided `file` path does not exist or is not a file.

    """
    file = Path(file).expanduser().resolve()

    if not file.is_file():
        raise FileNotFoundError(file)

    filename = name if name else file.name
    content = file.read_bytes()

    return cls(content=content, name=filename)

from_data_url classmethod

from_data_url(*, url: str, name: str) -> Self

Create an Attachment from a data URL.

Parameters:

Name Type Description Default
url str

Attachment content as a data URL.

required
name str

The desired name for the attachment.

required

Returns:

Type Description
Self

Raises:

Type Description
ValueError

If the provided url is not a data URL.

Source code in src/privatebin/_models.py
@classmethod
def from_data_url(cls, *, url: str, name: str) -> Self:
    """
    Create an Attachment from a [data URL][Data URL].

    [data URL]: https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data

    Parameters
    ----------
    url : str
        Attachment content as a data URL.
    name : str
        The desired name for the attachment.

    Returns
    -------
    Self

    Raises
    ------
    ValueError
        If the provided `url` is not a data URL.

    """
    # https://regex101.com/r/Wiu431/1
    pattern = r"^data:(?P<mimetype>.+);base64,(?P<data>.+)$"
    match = re.fullmatch(pattern, url)

    if match is None:
        truncated = url[:50] + "... (TRUNCATED)" if len(url) > 50 else url  # noqa: PLR2004
        msg = (
            "Paste has an invalid or unsupported attachment. "
            f"Expected a data URL: 'data:<mimetype>;base64,<data>', got: {truncated!r}"
        )
        raise ValueError(msg)

    data = match.group("data")
    content = base64.b64decode(data)

    return cls(content=content, name=name)

to_data_url

to_data_url() -> str

Convert the Attachment's binary content to a data URL.

Returns:

Type Description
str

A data URL representing the attachment content.

Source code in src/privatebin/_models.py
def to_data_url(self) -> str:
    """
    Convert the Attachment's binary content to a [data URL][Data URL].

    [Data URL]: https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data

    Returns
    -------
    str
        A data URL representing the attachment content.

    """
    encoded = base64.b64encode(self.content).decode()
    mimetype = guess_mime_type(self.name)
    return f"data:{mimetype};base64,{encoded}"

from_json classmethod

from_json(data: str) -> Self

Create an Attachment instance from a JSON string.

Parameters:

Name Type Description Default
data str

JSON string representing the Attachment instance.

required

Returns:

Type Description
Self
Source code in src/privatebin/_models.py
@classmethod
def from_json(cls, data: str, /) -> Self:
    """
    Create an Attachment instance from a JSON string.

    Parameters
    ----------
    data : str
        JSON string representing the Attachment instance.

    Returns
    -------
    Self

    """
    return msgspec.json.decode(data, type=cls)

to_json

to_json(*, indent: int = 2) -> str

Serialize the Attachment instance into a JSON string. The content (binary data) will be a base64 encoded string in the JSON output.

Parameters:

Name Type Description Default
indent int

Number of spaces for indentation. Set to 0 for a single line with spacing, or negative to minimize size by removing extra whitespace.

2

Returns:

Type Description
str

JSON string representing the Attachment.

Source code in src/privatebin/_models.py
def to_json(self, *, indent: int = 2) -> str:
    """
    Serialize the Attachment instance into a JSON string.
    The `content` (binary data) will be a base64 encoded string in the JSON output.

    Parameters
    ----------
    indent : int, optional
        Number of spaces for indentation.
        Set to 0 for a single line with spacing,
        or negative to minimize size by removing extra whitespace.

    Returns
    -------
    str
        JSON string representing the Attachment.

    """
    jsonified = msgspec.json.encode(self).decode()
    return msgspec.json.format(jsonified, indent=indent)

Paste

Bases: Struct

Represents a PrivateBin paste.

id instance-attribute

id: str

Unique identifier for the paste.

text instance-attribute

text: str

The decrypted text content of the paste.

attachment instance-attribute

attachment: Attachment | None

Attachment associated with the paste, if any.

formatter instance-attribute

formatter: Formatter

Formatting option applied to the paste content.

open_discussion instance-attribute

open_discussion: bool

Indicates if open discussions are enabled for this paste.

burn_after_reading instance-attribute

burn_after_reading: bool

Indicates if the paste is set to be burned after the first read.

time_to_live instance-attribute

time_to_live: timedelta | None

Time duration for which the paste is set to be stored, if any.

from_json classmethod

from_json(data: str) -> Self

Create an Paste instance from a JSON string.

Parameters:

Name Type Description Default
data str

JSON string representing the Paste instance.

required

Returns:

Type Description
Self
Source code in src/privatebin/_models.py
@classmethod
def from_json(cls, data: str, /) -> Self:
    """
    Create an Paste instance from a JSON string.

    Parameters
    ----------
    data : str
        JSON string representing the Paste instance.

    Returns
    -------
    Self

    """
    return msgspec.json.decode(data, type=cls)

to_json

to_json(*, indent: int = 2) -> str

Serialize the Paste instance into a JSON string.

Parameters:

Name Type Description Default
indent int

Number of spaces for indentation. Set to 0 for a single line with spacing, or negative to minimize size by removing extra whitespace.

2

Returns:

Type Description
str

JSON string representing the Paste.

Source code in src/privatebin/_models.py
def to_json(self, *, indent: int = 2) -> str:
    """
    Serialize the Paste instance into a JSON string.

    Parameters
    ----------
    indent : int, optional
        Number of spaces for indentation.
        Set to 0 for a single line with spacing,
        or negative to minimize size by removing extra whitespace.

    Returns
    -------
    str
        JSON string representing the Paste.

    """
    jsonified = msgspec.json.encode(self).decode()
    return msgspec.json.format(jsonified, indent=indent)

PrivateBinUrl

Bases: Struct

Represents a parsed PrivateBin URL, including its components and delete token.

server instance-attribute

server: str

The base server URL of the PrivateBin instance.

id instance-attribute

id: str

The unique paste ID. This identifies the specific paste on the server.

passphrase instance-attribute

passphrase: str

The decryption passphrase. This is needed to decrypt and view encrypted pastes.

delete_token instance-attribute

delete_token: str

The delete token. Authorizes deletion of the paste.

to_str

to_str() -> str

Explicitly convert the instance into a complete, unmasked URL string.

This method behaves differently from implicit Python string conversions like print(url), or f-strings (f"{url}").

  • to_str() returns the full, unmasked URL with the sensitive passphrase.
  • Implicit conversions (print(), f-strings, etc.) return a masked URL for safety.

Call to_str() when you explicitly need the full, working URL, for example, to:

  • Open the URL in a browser.
  • Pass the URL to a function that requires the unmasked passphrase.

Returns:

Type Description
str

The full, unmasked PrivateBin URL.

Examples:

>>> url = PrivateBinUrl(server="https://example.privatebin.com/", id="pasteid", passphrase="secret", delete_token="deltoken")
>>> url.to_str()
'https://example.privatebin.com/?pasteid#secret'
>>> print(url)  # Implicit string conversion - masked URL
'https://example.privatebin.com/?pasteid#********'
>>> f"{url}"  # Implicit string conversion in f-string - masked URL
'https://example.privatebin.com/?pasteid#********'
Source code in src/privatebin/_models.py
def to_str(self) -> str:
    """
    Explicitly convert the instance into a complete, unmasked URL string.

    This method behaves differently from implicit Python string conversions
    like `print(url)`, or f-strings (`f"{url}"`).

    -  `to_str()` returns the full, unmasked URL with the sensitive passphrase.
    -  Implicit conversions (`print()`, f-strings, etc.) return a masked URL for safety.

    Call `to_str()` when you explicitly need the full, working URL, for example, to:

    -  Open the URL in a browser.
    -  Pass the URL to a function that requires the unmasked passphrase.

    Returns
    -------
    str
        The full, unmasked PrivateBin URL.

    Examples
    --------
    >>> url = PrivateBinUrl(server="https://example.privatebin.com/", id="pasteid", passphrase="secret", delete_token="deltoken")
    >>> url.to_str()
    'https://example.privatebin.com/?pasteid#secret'
    >>> print(url)  # Implicit string conversion - masked URL
    'https://example.privatebin.com/?pasteid#********'
    >>> f"{url}"  # Implicit string conversion in f-string - masked URL
    'https://example.privatebin.com/?pasteid#********'

    """
    return urljoin(self.server, f"/?{self.id}#{self.passphrase}")

from_json classmethod

from_json(data: str) -> Self

Create an PrivateBinUrl instance from a JSON string.

Parameters:

Name Type Description Default
data str

JSON string representing the PrivateBinUrl instance.

required

Returns:

Type Description
Self
Source code in src/privatebin/_models.py
@classmethod
def from_json(cls, data: str, /) -> Self:
    """
    Create an PrivateBinUrl instance from a JSON string.

    Parameters
    ----------
    data : str
        JSON string representing the PrivateBinUrl instance.

    Returns
    -------
    Self

    """
    return msgspec.json.decode(data, type=cls)

to_json

to_json(*, indent: int = 2) -> str

Serialize the PrivateBinUrl instance into a JSON string.

Parameters:

Name Type Description Default
indent int

Number of spaces for indentation. Set to 0 for a single line with spacing, or negative to minimize size by removing extra whitespace.

2

Returns:

Type Description
str

JSON string representing the PrivateBinUrl.

Notes

This method includes the sensitive passphrase in the JSON output. It also adds an extra field named "url" to the JSON, which is not part of PrivateBinUrl but is generated using the to_str() method for convenience.

Source code in src/privatebin/_models.py
def to_json(self, *, indent: int = 2) -> str:
    """
    Serialize the PrivateBinUrl instance into a JSON string.

    Parameters
    ----------
    indent : int, optional
        Number of spaces for indentation.
        Set to 0 for a single line with spacing,
        or negative to minimize size by removing extra whitespace.

    Returns
    -------
    str
        JSON string representing the PrivateBinUrl.

    Notes
    -----
    This method includes the sensitive `passphrase` in the JSON output.
    It also adds an extra field named `"url"` to the JSON, which is not part of
    `PrivateBinUrl` but is generated using the `to_str()` method for convenience.

    """
    basic = msgspec.to_builtins(self)
    # Add the full URL to the JSON output
    basic["url"] = self.to_str()
    jsonified = msgspec.json.encode(basic).decode()
    return msgspec.json.format(jsonified, indent=indent)