kdbxtool.models

Data models for KDBX database elements.

This module provides typed Python classes for representing KDBX database contents: entries, groups, and the database itself.

class kdbxtool.models.Attachment(filename, id, entry)[source]

Bases: object

An attachment (binary file) associated with an entry.

Attachments represent files attached to entries in the database. The binary data is stored at the database level and referenced by ID.

Parameters:
filename

Name of the attached file

Type:

str

id

Reference ID to the binary data in the database

Type:

int

entry

The entry this attachment belongs to

Type:

Entry

__init__(filename, id, entry)
Parameters:
Return type:

None

property data: bytes | None

Get the binary data for this attachment.

Returns:

Binary data if available, None if not found or entry has no database

filename: str
id: int
entry: Entry
class kdbxtool.models.Entry(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)[source]

Bases: object

A password entry in a KDBX database.

Entries store credentials and associated metadata. Each entry has standard fields (title, username, password, url, notes) plus support for custom string fields and binary attachments.

Parameters:
uuid

Unique identifier for the entry

Type:

uuid_module.UUID

times

Timestamps (creation, modification, access, expiry)

Type:

Times

icon_id

Icon ID for display (standard icon)

Type:

str

custom_icon_uuid

UUID of custom icon (overrides icon_id if set)

Type:

uuid_module.UUID | None

tags

List of tags for categorization

Type:

list[str]

strings

Dictionary of string fields (key -> StringField)

Type:

dict[str, StringField]

binaries

List of binary attachment references

Type:

list[BinaryRef]

autotype

AutoType settings

Type:

AutoType

history

List of previous versions of this entry

Type:

list[HistoryEntry]

foreground_color

Custom foreground color (hex)

Type:

str | None

background_color

Custom background color (hex)

Type:

str | None

override_url

URL override for AutoType

Type:

str | None

quality_check

Whether to check password quality

Type:

bool

__init__(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)
Parameters:
Return type:

None

background_color: str | None = None
clear_history()[source]

Clear all history entries.

This is a convenience method equivalent to delete_history(all=True).

Return type:

None

classmethod create(title=None, username=None, password=None, url=None, notes=None, tags=None, icon_id='0', expires=False, expiry_time=None)[source]

Create a new entry with common fields.

Parameters:
  • title (str | None) – Entry title

  • username (str | None) – Username

  • password (str | None) – Password

  • url (str | None) – URL

  • notes (str | None) – Notes

  • tags (list[str] | None) – List of tags

  • icon_id (str) – Icon ID

  • expires (bool) – Whether entry expires

  • expiry_time (datetime | None) – Expiration time

Returns:

New Entry instance

Return type:

Entry

property custom_icon: UUID | None

Get or set custom icon by UUID or name.

When setting, accepts either a UUID or an icon name (string). If a string is provided, it must match exactly one icon name in the database. Requires the entry to be associated with a database for name-based lookup.

Returns:

UUID of the custom icon, or None if not set

custom_icon_uuid: uuid_module.UUID | None = None
property custom_properties: dict[str, str | None]

Get all custom properties as a dictionary.

property database: Database | None

Get the database this entry belongs to.

delete_custom_property(key)[source]

Delete a custom property.

Parameters:

key (str) – Property name to delete

Raises:
Return type:

None

delete_history(history_entry=None, *, all=False)[source]

Delete history entries.

Either deletes a specific history entry or all history entries. At least one of history_entry or all=True must be specified.

Parameters:
  • history_entry (HistoryEntry | None) – Specific history entry to delete

  • all (bool) – If True, delete all history entries

Raises:
  • ValueError – If neither history_entry nor all=True is specified

  • ValueError – If history_entry is not in this entry’s history

Return type:

None

deref(field)[source]

Resolve any field references in the given field’s value.

If the field’s value contains KeePass field references ({REF:X@Y:Z}), resolves them to the actual values from the referenced entries.

Parameters:

field (str) – One of ‘title’, ‘username’, ‘password’, ‘url’, ‘notes’

Returns:

The resolved value with all references replaced, a UUID if the referenced field is ‘uuid’, or None if a referenced entry is not found

Raises:

ValueError – If no database reference is available

Return type:

str | UUID | None

Example

>>> # If entry.password contains '{REF:P@I:...UUID...}'
>>> actual_password = entry.deref('password')
dump()[source]

Return a human-readable summary of the entry for debugging.

Returns:

Multi-line string with entry details (passwords are masked).

Return type:

str

property expired: bool

Check if entry has expired.

foreground_color: str | None = None
get_custom_property(key)[source]

Get a custom property value.

Parameters:

key (str) – Property name (must not be a reserved key)

Returns:

Property value, or None if not set

Raises:

ValueError – If key is a reserved key

Return type:

str | None

icon_id: str = '0'
property index: int

Get the index of this entry within its parent group.

Returns:

Zero-based index of this entry in the parent’s entries list.

Raises:

ValueError – If entry has no parent group.

move_to(destination)[source]

Move this entry to a different group.

Removes the entry from its current parent and adds it to the destination group. Updates the location_changed timestamp.

Parameters:

destination (Group) – Target group to move the entry to

Raises:
  • ValueError – If entry has no parent (not yet added to a group)

  • ValueError – If destination is the current parent (no-op would be confusing)

Return type:

None

property notes: str | None

Get or set entry notes.

property otp: str | None

Get or set OTP secret (TOTP/HOTP).

override_url: str | None = None
property parent: Group | None

Get parent group.

property password: str | None

Get or set entry password.

quality_check: bool = True
ref(field)[source]

Create a reference string pointing to a field of this entry.

Creates a KeePass field reference string that can be used in other entries to reference values from this entry. References use the entry’s UUID for lookup.

Parameters:

field (str) – One of ‘title’, ‘username’, ‘password’, ‘url’, ‘notes’, or ‘uuid’

Returns:

X@I:UUID}

Return type:

Field reference string in format {REF

Raises:

ValueError – If field is not a valid field name

Example

>>> main_entry = db.find_entries(title='Main Account', first=True)
>>> ref_string = main_entry.ref('password')
>>> # Returns '{REF:P@I:...UUID...}'
>>> other_entry.password = ref_string
reindex(new_index)[source]

Move this entry to a new position within its parent group.

Parameters:

new_index (int) – Target position (zero-based). Negative indices are supported (e.g., -1 for last position).

Raises:
Return type:

None

save_history()[source]

Save current state to history before making changes.

Return type:

None

set_custom_property(key, value, protected=False)[source]

Set a custom property.

Parameters:
  • key (str) – Property name (must not be a reserved key)

  • value (str) – Property value

  • protected (bool) – Whether to mark as protected in memory

Raises:

ValueError – If key is a reserved key

Return type:

None

property title: str | None

Get or set entry title.

totp(*, at=None)[source]

Generate current TOTP code from the entry’s otp field.

Supports both standard otpauth:// URIs and KeePassXC legacy format (TOTP Seed / TOTP Settings custom fields).

Parameters:

at (datetime | float | None) – Optional timestamp for code generation. Can be a datetime or Unix timestamp float. Defaults to current time.

Returns:

TotpCode object with code and expiration info, or None if no OTP configured.

Raises:

ValueError – If OTP configuration is invalid

Return type:

TotpCode | None

Example

>>> result = entry.totp()
>>> print(f"Code: {result.code}")
Code: 123456
>>> print(f"Expires in {result.remaining}s")
Expires in 15s
>>> # TotpCode also works as a string
>>> print(result)
123456
touch(modify=False)[source]

Update access time, optionally modification time.

Parameters:

modify (bool)

Return type:

None

property url: str | None

Get or set entry URL.

property username: str | None

Get or set entry username.

uuid: uuid_module.UUID
times: Times
tags: list[str]
strings: dict[str, StringField]
binaries: list[BinaryRef]
autotype: AutoType
history: list[HistoryEntry]
class kdbxtool.models.Group(uuid=<factory>, name=None, notes=None, times=<factory>, icon_id='48', custom_icon_uuid=None, is_expanded=True, default_autotype_sequence=None, enable_autotype=None, enable_searching=None, last_top_visible_entry=None, entries=<factory>, subgroups=<factory>, _parent=None, _is_root=False, _database=None)[source]

Bases: object

A group (folder) in a KDBX database.

Groups organize entries into a hierarchical structure. Each group can contain entries and subgroups.

Parameters:
  • uuid (uuid_module.UUID)

  • name (str | None)

  • notes (str | None)

  • times (Times)

  • icon_id (str)

  • custom_icon_uuid (uuid_module.UUID | None)

  • is_expanded (bool)

  • default_autotype_sequence (str | None)

  • enable_autotype (bool | None)

  • enable_searching (bool | None)

  • last_top_visible_entry (uuid_module.UUID | None)

  • entries (list[Entry])

  • subgroups (list[Group])

  • _parent (Group | None)

  • _is_root (bool)

  • _database (Database | None)

uuid

Unique identifier for the group

Type:

uuid_module.UUID

name

Display name of the group

Type:

str | None

notes

Optional notes/description

Type:

str | None

times

Timestamps (creation, modification, access, expiry)

Type:

Times

icon_id

Icon ID for display (standard icon)

Type:

str

custom_icon_uuid

UUID of custom icon (overrides icon_id if set)

Type:

uuid_module.UUID | None

is_expanded

Whether group is expanded in UI

Type:

bool

default_autotype_sequence

Default AutoType sequence for entries

Type:

str | None

enable_autotype

Whether AutoType is enabled for this group

Type:

bool | None

enable_searching

Whether entries in this group are searchable

Type:

bool | None

last_top_visible_entry

UUID of last visible entry (UI state)

Type:

uuid_module.UUID | None

entries

List of entries in this group

Type:

list[Entry]

subgroups

List of subgroups

Type:

list[Group]

__init__(uuid=<factory>, name=None, notes=None, times=<factory>, icon_id='48', custom_icon_uuid=None, is_expanded=True, default_autotype_sequence=None, enable_autotype=None, enable_searching=None, last_top_visible_entry=None, entries=<factory>, subgroups=<factory>, _parent=None, _is_root=False, _database=None)
Parameters:
  • uuid (uuid_module.UUID)

  • name (str | None)

  • notes (str | None)

  • times (Times)

  • icon_id (str)

  • custom_icon_uuid (uuid_module.UUID | None)

  • is_expanded (bool)

  • default_autotype_sequence (str | None)

  • enable_autotype (bool | None)

  • enable_searching (bool | None)

  • last_top_visible_entry (uuid_module.UUID | None)

  • entries (list[Entry])

  • subgroups (list[Group])

  • _parent (Group | None)

  • _is_root (bool)

  • _database (Database | None)

Return type:

None

add_entry(entry)[source]

Add an entry to this group.

Parameters:

entry (Entry) – Entry to add

Returns:

The added entry

Return type:

Entry

add_subgroup(group)[source]

Add a subgroup to this group.

Parameters:

group (Group) – Group to add

Returns:

The added group

Return type:

Group

create_entry(title=None, username=None, password=None, url=None, notes=None, tags=None, *, template=None)[source]

Create and add a new entry to this group.

Parameters:
  • title (str | None) – Entry title

  • username (str | None) – Username

  • password (str | None) – Password

  • url (str | None) – URL

  • notes (str | None) – Notes

  • tags (list[str] | None) – Tags

  • template (EntryTemplate | None) – Optional entry template instance with field values

Returns:

Newly created entry

Return type:

Entry

Example

>>> # Standard entry (no template)
>>> entry = group.create_entry(title="Site", username="user", password="pass")
>>> # Using a template with typed fields
>>> from kdbxtool import Templates
>>> entry = group.create_entry(
...     title="My Visa",
...     template=Templates.CreditCard(
...         card_number="4111111111111111",
...         expiry_date="12/25",
...         cvv="123",
...     ),
... )
>>> # Server template with standard fields
>>> entry = group.create_entry(
...     title="prod-server",
...     username="admin",
...     password="secret",
...     template=Templates.Server(
...         hostname="192.168.1.1",
...         port="22",
...     ),
... )
classmethod create_root(name='Root')[source]

Create a root group for a new database.

Parameters:

name (str) – Name for the root group

Returns:

New root Group instance

Return type:

Group

create_subgroup(name, notes=None, icon_id='48')[source]

Create and add a new subgroup.

Parameters:
  • name (str) – Group name

  • notes (str | None) – Optional notes

  • icon_id (str) – Icon ID

Returns:

Newly created group

Return type:

Group

property custom_icon: UUID | None

Get or set custom icon by UUID or name.

When setting, accepts either a UUID or an icon name (string). If a string is provided, it must match exactly one icon name in the database. Requires the group to be associated with a database for name-based lookup.

Returns:

UUID of the custom icon, or None if not set

custom_icon_uuid: uuid_module.UUID | None = None
property database: Database | None

Get the database this group belongs to.

default_autotype_sequence: str | None = None
dump(recursive=False)[source]

Return a human-readable summary of the group for debugging.

Parameters:

recursive (bool) – If True, include subgroups and entries recursively

Returns:

Multi-line string with group details.

Return type:

str

enable_autotype: bool | None = None
enable_searching: bool | None = None
property expired: bool

Check if group has expired.

find_entries(title=None, username=None, password=None, url=None, notes=None, otp=None, tags=None, string=None, autotype_enabled=None, autotype_sequence=None, autotype_window=None, recursive=True, history=False)[source]

Find entries matching criteria.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Match entries with this title (exact)

  • username (str | None) – Match entries with this username (exact)

  • password (str | None) – Match entries with this password (exact)

  • url (str | None) – Match entries with this URL (exact)

  • notes (str | None) – Match entries with these notes (exact)

  • otp (str | None) – Match entries with this OTP (exact)

  • tags (list[str] | None) – Match entries containing all these tags

  • string (dict[str, str] | None) – Match entries with custom properties (dict of key:value)

  • autotype_enabled (bool | None) – Filter by AutoType enabled state

  • autotype_sequence (str | None) – Match entries with this AutoType sequence (exact)

  • autotype_window (str | None) – Match entries with this AutoType window (exact)

  • recursive (bool) – Search in subgroups

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Return type:

list[Entry]

find_entries_contains(title=None, username=None, password=None, url=None, notes=None, otp=None, recursive=True, case_sensitive=False, history=False)[source]

Find entries where fields contain the given substrings.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Match entries whose title contains this substring

  • username (str | None) – Match entries whose username contains this substring

  • password (str | None) – Match entries whose password contains this substring

  • url (str | None) – Match entries whose URL contains this substring

  • notes (str | None) – Match entries whose notes contain this substring

  • otp (str | None) – Match entries whose OTP contains this substring

  • recursive (bool) – Search in subgroups

  • case_sensitive (bool) – If False (default), matching is case-insensitive

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Return type:

list[Entry]

find_entries_regex(title=None, username=None, password=None, url=None, notes=None, otp=None, recursive=True, case_sensitive=False, history=False)[source]

Find entries where fields match the given regex patterns.

All criteria are combined with AND logic. None means “any value”.

Parameters:
  • title (str | None) – Regex pattern to match against title

  • username (str | None) – Regex pattern to match against username

  • password (str | None) – Regex pattern to match against password

  • url (str | None) – Regex pattern to match against URL

  • notes (str | None) – Regex pattern to match against notes

  • otp (str | None) – Regex pattern to match against OTP

  • recursive (bool) – Search in subgroups

  • case_sensitive (bool) – If False (default), matching is case-insensitive

  • history (bool) – Include history entries in search

Returns:

List of matching entries

Raises:

re.error – If any pattern is not a valid regex

Return type:

list[Entry]

find_entry_by_uuid(uuid, recursive=True)[source]

Find an entry by UUID.

Parameters:
  • uuid (UUID) – Entry UUID to find

  • recursive (bool) – Search in subgroups

Returns:

Entry if found, None otherwise

Return type:

Entry | None

find_group_by_uuid(uuid, recursive=True)[source]

Find a group by UUID.

Parameters:
  • uuid (UUID) – Group UUID to find

  • recursive (bool) – Search in nested subgroups

Returns:

Group if found, None otherwise

Return type:

Group | None

find_groups(name=None, recursive=True, first=False)[source]

Find groups matching criteria.

Parameters:
  • name (str | None) – Match groups with this name (exact)

  • recursive (bool) – Search in nested subgroups

  • first (bool) – If True, return first matching group or None instead of list

Returns:

List of matching groups, or single Group/None if first=True

Return type:

list[Group] | Group | None

icon_id: str = '48'
property index: int

Get the index of this group within its parent group.

Returns:

Zero-based index of this group in the parent’s subgroups list.

Raises:

ValueError – If group has no parent (is root group).

is_expanded: bool = True
property is_root_group: bool

Check if this is the database root group.

iter_entries(recursive=True, history=False)[source]

Iterate over entries in this group.

Parameters:
  • recursive (bool) – If True, include entries from all subgroups

  • history (bool) – If True, include history entries

Yields:

Entry objects

Return type:

Iterator[Entry]

iter_groups(recursive=True)[source]

Iterate over subgroups.

Parameters:

recursive (bool) – If True, include nested subgroups

Yields:

Group objects

Return type:

Iterator[Group]

last_top_visible_entry: uuid_module.UUID | None = None
move_to(destination)[source]

Move this group to a different parent group.

Removes the group from its current parent and adds it to the destination group. Updates the location_changed timestamp.

Parameters:

destination (Group) – Target parent group to move this group to

Raises:
  • ValueError – If this is the root group (cannot be moved)

  • ValueError – If group has no parent (not yet added to a database)

  • ValueError – If destination is the current parent

  • ValueError – If destination is this group (cannot move into self)

  • ValueError – If destination is a descendant of this group (would create cycle)

Return type:

None

name: str | None = None
notes: str | None = None
property parent: Group | None

Get parent group, or None if this is the root.

property path: list[str]

Get path from root to this group.

Returns:

List of group names from root (exclusive) to this group (inclusive). Empty list for the root group.

reindex(new_index)[source]

Move this group to a new position within its parent group.

Parameters:

new_index (int) – Target position (zero-based). Negative indices are supported (e.g., -1 for last position).

Raises:
  • ValueError – If group has no parent (is root group).

  • IndexError – If new_index is out of range.

Return type:

None

remove_entry(entry)[source]

Remove an entry from this group.

Parameters:

entry (Entry) – Entry to remove

Raises:

ValueError – If entry is not in this group

Return type:

None

remove_subgroup(group)[source]

Remove a subgroup from this group.

Parameters:

group (Group) – Group to remove

Raises:

ValueError – If group is not a subgroup of this group

Return type:

None

touch(modify=False)[source]

Update access time, optionally modification time.

Parameters:

modify (bool)

Return type:

None

uuid: uuid_module.UUID
times: Times
entries: list[Entry]
subgroups: list[Group]
class kdbxtool.models.HistoryEntry(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)[source]

Bases: Entry

A historical version of an entry.

History entries are snapshots of an entry at a previous point in time. They share the same UUID as their parent entry.

Parameters:
__init__(uuid=<factory>, times=<factory>, icon_id='0', custom_icon_uuid=None, tags=<factory>, strings=<factory>, binaries=<factory>, autotype=<factory>, history=<factory>, foreground_color=None, background_color=None, override_url=None, quality_check=True, _parent=None, _database=None)
Parameters:
Return type:

None

classmethod from_entry(entry)[source]

Create a history entry from an existing entry.

Parameters:

entry (Entry) – Entry to create history from

Returns:

New HistoryEntry with copied data

Return type:

HistoryEntry

class kdbxtool.models.Times(creation_time=<factory>, last_modification_time=<factory>, last_access_time=<factory>, expiry_time=None, expires=False, usage_count=0, location_changed=None)[source]

Bases: object

Timestamps associated with entries and groups.

All times are stored as timezone-aware UTC datetimes.

Parameters:
creation_time

When the element was created

Type:

datetime.datetime

last_modification_time

When the element was last modified

Type:

datetime.datetime

last_access_time

When the element was last accessed

Type:

datetime.datetime

expiry_time

When the element expires (if expires is True)

Type:

datetime.datetime | None

expires

Whether the element can expire

Type:

bool

usage_count

Number of times the element has been used

Type:

int

location_changed

When the element was moved to a different group

Type:

datetime.datetime | None

__init__(creation_time=<factory>, last_modification_time=<factory>, last_access_time=<factory>, expiry_time=None, expires=False, usage_count=0, location_changed=None)
Parameters:
Return type:

None

classmethod create_new(expires=False, expiry_time=None)[source]

Create timestamps for a new element.

Parameters:
  • expires (bool) – Whether the element can expire

  • expiry_time (datetime | None) – When the element expires

Returns:

New Times instance with current timestamps

Return type:

Times

property expired: bool

Check if the element has expired.

Returns:

True if expires is True and expiry_time is in the past

expires: bool = False
expiry_time: datetime | None = None
increment_usage()[source]

Increment usage count and update access time.

Return type:

None

location_changed: datetime | None = None
touch(modify=False)[source]

Update access time, and optionally modification time.

Parameters:

modify (bool) – If True, also update modification time

Return type:

None

update_location()[source]

Update location_changed timestamp when element is moved.

Return type:

None

usage_count: int = 0
creation_time: datetime
last_modification_time: datetime
last_access_time: datetime

Modules

attachment

Attachment model for KDBX binary attachments.

entry

Entry model for KDBX password entries.

group

Group model for KDBX database folders.

times

Timestamp handling for KDBX elements.