Skip to content

Reference

kwai

kwai is the main package of the backend.

api

Main package for the API.

app

Module that implements a factory method for a FastAPI application.

configure_logger(settings)

Configure the logger.

create_app(settings=None)

Create the FastAPI application.

Parameters:

Name Type Description Default
settings Settings | None

Settings to use in this application.

None

When settings is None (the default), the dependency container will load the settings.

lifespan(app) async

Log the start/stop of the application.

converter

Module that defines an interface for a document converter.

DocumentConverter

Bases: ABC

Interface for a document converter.

A converter will convert a certain format (markdown for example) into HTML.

convert(content) abstractmethod

Convert a string to HTML.

MarkdownConverter

Bases: DocumentConverter

Converter for converting markdown into HTML.

convert(content)

Convert markdown to HTML.

dependencies

Module that integrates the dependencies in FastAPI.

get_current_user(settings=deps.depends(Settings), db=deps.depends(Database), token=Depends(oauth)) async

Try to get the current user from the access token.

Not authorized will be raised when the access token is not found, expired, revoked or when the user is revoked.

schemas

Package that contains all schemas used in the API.

application

Schemas for an application resource.

ApplicationResource

Represents a JSON:API resource for applications.

get_created_at()

Get the timestamp of creation.

get_description()

Get the description of the application.

get_events()

Check if this application can contain events.

get_id()

Get the id of the application.

get_name()

Get the name of the application.

get_news()

Check if this application can contain news stories.

get_pages()

Check if this application can contain pages.

get_remark()

Get the remark about the application.

get_short_description()

Get the short description the application.

get_title()

Get the title of the application.

get_updated_at()

Get the timestamp of the last update.

get_weight()

Get the weight of the application.

user_invitation

Schemas for a user invitation resource.

UserInvitationResource

Represent a JSON:API resource for a user invitation.

get_confirmed_at()

Get the timestamp of confirmation.

get_created_at()

Get the timestamp of creation.

get_email()

Get the email address for the invitation.

get_expired_at()

Get the timestamp of expiration.

get_first_name()

Get the first name of the receiver.

get_id()

Get the id of the user invitation.

get_last_name()

Get the last name of the receiver.

get_remark()

Get a remark about the invitation.

get_updated_at()

Get the timestamp of the last update.

v1

Package for version 1 of the API.

auth

Package for the auth API.

api

Module that defines the auth apis.

endpoints

Package that contains endpoints for authentication.

login

Module that implements all APIs for login.

TokenSchema

Bases: BaseModel

The response schema for an access/refresh token.

Attributes:

Name Type Description
access_token str
refresh_token str
expiration str

Timestamp in format YYYY-MM-DD HH:MM:SS

login(settings=deps.depends(Settings), db=deps.depends(Database), form_data=Depends()) async

Login a user.

The response is a TokenSchema.

Note

This request expects a form (application/x-www-form-urlencoded).

Parameters:

Name Type Description Default
settings

Settings dependency

deps.depends(Settings)
db

Database dependency

deps.depends(Database)
form_data OAuth2PasswordRequestForm

Form data that contains the username and password

Depends()
logout(settings=deps.depends(Settings), db=deps.depends(Database), user=Depends(get_current_user), refresh_token=Form()) async

Log out the current user.

A user is logged out by revoking the refresh token. The associated access token will also be revoked.

Parameters:

Name Type Description Default
settings

Settings dependency

deps.depends(Settings)
db Database

Database dependency

deps.depends(Database)
user UserEntity

The currently logged-in user

Depends(get_current_user)
refresh_token str

The active refresh token of the user

Form()

Returns:

Type Description

Http code 200 on success, 401 when the user is not logged in,

404 when the refresh token is not found.

recover_user(email=Form(), db=deps.depends(Database), bus=deps.depends(Bus)) async

Start a recover password flow for the given email address.

A mail with a unique id will be sent using the message bus.

Note

To avoid leaking information, this api will always respond with 200

Parameters:

Name Type Description Default
email(str)

The email of the user that wants to reset the password.

required
db(Database)

Database dependency

required
bus(Bus)

A message bus used to publish the event

required
renew_access_token(settings=deps.depends(Settings), db=deps.depends(Database), refresh_token=Form()) async

Refresh the access token.

Parameters:

Name Type Description Default
settings(Settings)

Settings dependency

required
db(Database)

Database dependency

required
refresh_token(str)

The active refresh token of the user

required

Returns:

Name Type Description
TokenSchema

On success a new TokenSchema is returned.

reset_password(uuid=Form(), password=Form(), db=deps.depends(Database)) async

Reset the password of the user.

Parameters:

Name Type Description Default
uuid(str)

The unique id of the password recovery.

required
password(str)

The new password

required
db(Database)

Database dependency

required

Returns:

Type Description

Http code 200 on success, 404 when the unique is invalid, 422 when the

request can't be processed, 403 when the request is forbidden.

user

Module that implements all user endpoints.

get(user=Depends(get_current_user))

Get the current user.

user_invitations

Module that implements invitations endpoints.

create_user_invitation(resource, db=deps.depends(Database), user=Depends(get_current_user), bus=deps.depends(Bus)) async

Create a user invitation.

delete_user_invitation(uuid, db=deps.depends(Database), user=Depends(get_current_user)) async

Delete the user invitation with the given unique id.

get_user_invitation(uuid, db=deps.depends(Database), user=Depends(get_current_user)) async

Get the user invitation with the given unique id.

get_user_invitations(pagination=Depends(PaginationModel), db=deps.depends(Database), user=Depends(get_current_user)) async

Get all user invitations.

portal

Package for the portal API.

api

Module that defines the portal api.

endpoints

Package that contains endpoints for the portal.

applications

Module that implements applications endpoints.

get_applications(db=deps.depends(Database)) async

Get all applications of kwai.

news

Module that implements news endpoints.

get_news(pagination=Depends(PaginationModel), db=deps.depends(Database)) async

Get news stories for the portal.

Only promoted news stories are returned for the portal.

schemas

Package for schemas of the portal.

story

Schemas for a story on a portal.

PortalApplicationResource

JSON:API resource for an application.

get_id()

Get the id.

get_name()

Get the name of the application.

get_title()

Get the title of the application.

PortalStoryResource

Represent a JSONAPI resource for a news story.

__init__(story)

Construct.

Parameters:

Name Type Description Default
story StoryEntity

The story news entity that is transformed into a JSONAPI resource.

required
get_application()

Get the application of the story.

get_content()

Get the content of the story.

get_id()

Get the id of the story.

get_priority()

Get the priority of the promotion.

get_publish_date()

Get the publication date.

StoryContent

Bases: BaseModel

Schema for the content of a story.

trainings

Package for the trainings API.

api

Module that defines the trainings API.

endpoints

Package for all endpoints of trainings API.

trainings

Module for endpoints for trainings.

TrainingsFilterModel

Bases: BaseModel

Define the JSON:API filter for trainings.

create_training(resource, db=deps.depends(Database), user=Depends(get_current_user)) async

Create a new training.

delete_training_definition(training_definition_id, resource, db=deps.depends(Database), user=Depends(get_current_user)) async

Delete a training definition.

get_training(training_id, db=deps.depends(Database)) async

Get the training with the given id.

get_trainings(pagination=Depends(PaginationModel), trainings_filter=Depends(TrainingsFilterModel), db=deps.depends(Database)) async

Get all trainings.

update_training(training_id, resource, db=deps.depends(Database), user=Depends(get_current_user)) async

Update a training.

schemas

Package for schemas of the trainings endpoint.

training

Schemas for training(s).

CoachResource

Represent a coach attached to a training.

get_id()

Get the id of the coach.

get_name()

Get the name of the coach.

TeamResource

Represent a team.

get_id()

Return the id of the team.

get_name()

Return the name of the team.

TrainingCoach

Bases: BaseModel

Schema for coach/training specific information.

TrainingContent

Bases: BaseModel

Schema for the content of a training.

TrainingEvent

Bases: BaseModel

Schema for the event information of a training.

TrainingResource

Represent a JSON:API resource for a training entity.

__init__(training)

Initialize a training resource.

Parameters:

Name Type Description Default
training TrainingEntity

The training entity that is transformed into a JSON:API resource.

required
get_coaches()

Get the coaches attached to the training.

get_contents()

Get the content of the training.

get_created_at()

Get the timestamp of creation.

get_definition()

Get the related training definition resource.

get_event()

Get the event information from a training.

get_id()

Get the id of the training.

get_remark()

Get the remark of the training.

get_teams()

Get the teams of the training.

get_training_coaches()

Get a list with coach data.

get_updated_at()

Get the timestamp of the last update.

training_definition

Module for the training definition schema.

TrainingDefinitionResource

JSON:API resource for a training definition.

__init__(training_definition)

Initialize a training definition resource.

Parameters:

Name Type Description Default
training_definition TrainingDefinitionEntity

the training definition entity that is transformed to a JSON:API resource.

required
get_active()

Get if the training definition is active.

get_created_at()

Get the timestamp of creation.

get_description()

Get the description of the training definition.

get_end_time()

Get the end time of the training definition.

get_id()

Return the id of the training definition.

get_location()

Get the location of the training definition.

get_name()

Get the name of the training definition.

get_remark()

Get the remark of the training definition.

get_start_time()

Get the start time of the training definition.

get_updated_at()

Get the timestamp of the last update.

get_weekday()

Get the week day of the training definition.

cli

Package that defines all commands for the CLI of kwai.

bus

bus contains subcommands for the event bus.

check()

Check if the environment variable is set. If not, stop the cli.

show(password=typer.Option(False, help='Show the password'))

Command for showing the active database settings.

Parameters:

Name Type Description Default
password bool

show or hide the password (default is hide).

typer.Option(False, help='Show the password')
stream(name=typer.Option(..., help='The name of the stream'), messages=typer.Option(False, help='List all messages'))

Command for getting information about a stream.

Parameters:

Name Type Description Default
name str

The name of the stream.

typer.Option(..., help='The name of the stream')
messages bool

List all messages or not? Default is False.

typer.Option(False, help='List all messages')
test()

Command for testing the redis connection.

db

db contains subcommands for the database.

check()

Check if the environment variable is set. If not, stop the cli.

show(password=typer.Option(False, help='Show the password'))

Command for showing the active database settings.

Parameters:

Name Type Description Default
password bool

show or hide the password (default is hide).

typer.Option(False, help='Show the password')
test()

Command for testing the database connection.

identity

Identity contains all subcommands for managing identity in kwai.

Note

Make sure the environment variable KWAI_SETTINGS_FILE is set!

check()

Check if the environment variable is set. If not, stop the cli.

create(email=typer.Option(..., help='The email address of the new user', prompt=True), first_name=typer.Option(..., help='The first name of the new user', prompt=True), last_name=typer.Option(..., help='The last name of the new user', prompt=True), password=typer.Option(..., prompt=True, confirmation_prompt=True, hide_input=True))

Create a user account.

Use this command to create a new user account (for the root user for example).

Parameters:

Name Type Description Default
email str

The email address of the new user

typer.Option(..., help='The email address of the new user', prompt=True)
first_name str

The firstname of the new user

typer.Option(..., help='The first name of the new user', prompt=True)
last_name str

The lastname of the new user

typer.Option(..., help='The last name of the new user', prompt=True)
password str

The password of the new user

typer.Option(..., prompt=True, confirmation_prompt=True, hide_input=True)

core

Package for all core modules.

db

Package for all database related modules.

ORM (Object-relational mapping) software (like SQLAlchemy) is not used. Instead, the repository pattern is used. A repository is responsible for saving, creating, querying and deleting entities. sql-smith is used to build queries.

The DatabaseQuery class can be used to implement the Query interface.

database

Module for database classes/functions.

Database

Class for communicating with a database.

Attributes:

Name Type Description
_connection Connection | None

A connection

_settings DatabaseSettings

The settings for this database connection.

settings: DatabaseSettings property

Return the database settings.

This property is immutable: the returned value is a copy of the current settings.

check_connection() async

Check if the connection is set, if not it will try to connect.

close() async

Close the connection.

commit() async

Commit all changes.

create_query_factory() classmethod

Return a query factory for the current database engine.

The query factory is used to start creating a SELECT, INSERT, UPDATE or DELETE query.

Returns:

Type Description
QueryFactory

The query factory from sql-smith. Currently, it returns a query factory for the mysql engine. In the future it can provide other engines.

delete(id_, table_name) async

Delete a row from the table using the id field.

Parameters:

Name Type Description Default
id_ Any

The id of the row to delete.

required
table_name str

The name of the table.

required

Raises:

Type Description
QueryException

Raised when the query results in an error.

execute(query) async

Execute a query.

The last rowid from the cursor is returned when the query executed successfully. On insert, this can be used to determine the new id of a row.

Parameters:

Name Type Description Default
query AbstractQuery

The query to execute.

required

Returns:

Type Description
int

When the query is an insert query, it will return the last rowid.

None

When there is no last rowid.

Raises:

Type Description
QueryException

Raised when the query contains an error.

fetch(query) async

Execute a query and yields each row.

Parameters:

Name Type Description Default
query SelectQuery

The query to execute.

required

Yields:

Type Description
Record

A row is a dictionary using the column names as key and the column values as value.

Raises:

Type Description
QueryException

Raised when the query contains an error.

fetch_one(query) async

Execute a query and return the first row.

Parameters:

Name Type Description Default
query SelectQuery

The query to execute.

required

Returns:

Type Description
Record

A row is a dictionary using the column names as key and the column values as value.

None

The query resulted in no rows found.

Raises:

Type Description
QueryException

Raised when the query contains an error.

insert(table_name, *table_data) async

Insert one or more instances of a dataclass into the given table.

Parameters:

Name Type Description Default
table_name str

The name of the table

required
table_data Any

One or more instances of a dataclass containing the values

()

Returns:

Type Description
int

The last inserted id. When multiple inserts are performed, this will be the id of the last executed insert.

Raises:

Type Description
QueryException

Raised when the query contains an error.

log_query(query)

Log a query.

Parameters:

Name Type Description Default
query str

The query to log.

required
setup() async

Set up the connection pool.

update(id_, table_name, table_data) async

Update a dataclass in the given table.

Parameters:

Name Type Description Default
id_ Any

The id of the data to update.

required
table_name str

The name of the table.

required
table_data Any

The dataclass containing the data.

required

Raises:

Type Description
QueryException

Raised when the query contains an error.

database_query

Module that implements a query for a database.

DatabaseQuery

Bases: Query

Creates a query using a database.

columns abstractmethod property

Returns the columns used in the query.

count_column: str property

The column used to count records.

count() async

Execute the query and counts the number of records.

The count_column is used as column for a distinct count.

fetch(limit=None, offset=None)

Fetch all records from this query.

fetch_one() async

Fetch only one record from this query.

init() abstractmethod

Override this method to create the base query.

exceptions

Module that defines all database related exceptions.

DatabaseException

Bases: Exception

Raised when a database error occurred.

QueryException

Bases: DatabaseException

Raised when the execution of a query failed.

sql: str property

Return the sql statement of the query.

rows

Module that defines common table classes.

ContentRow dataclass

Represent a row for a content table.

Attributes:

Name Type Description
locale str

The code of the locale of the text

format str

The format of the text (md = markdown, html, ...)

title str

The title of the news story

content str

The long content of the news story

summary str

A summary of the content

user_id int

The id of the author

created_at datetime

the timestamp of creation

updated_at datetime | None

the timestamp of the last modification

create_content(author)

Create a Content value object from a row.

Parameters:

Name Type Description Default
author Owner

The author of the content.

required
OwnerRow dataclass

Represent the owner data.

create_owner()

Create an Author value object from row data.

table

Module for the table decorator.

Table

Bases: Generic[T]

Represent a table in the database.

With this class a table row can be transformed into a dataclass. It can also be used to generate columns or aliases for queries.

table_name: str property

Return the table name.

__call__(row, table_name=None)

Shortcut for map_row.

alias_name(column_name, table_name=None)

Return an alias for a column.

The alias will be the name of the table delimited with an underscore: _. By default, the table name associated with the Table instance will be used.

Parameters:

Name Type Description Default
column_name str

The name of the column

required
table_name str | None

To differ from the current table name, use this table name.

None

Returns:

Type Description

The alias for the given column.

aliases(table_name=None)

Return aliases for all fields of the dataclass.

column(column_name)

Return column as

..

field(column_name)

Call sql-smith field with the given column.

short-cut for: field(table.table_name + '.' + column_name)

map_row(row, table_name=None)

Map the data of a row to the dataclass.

Only the fields that have the alias prefix for this table will be selected. This makes it possible to pass it a row that contains data from multiple tables (which can be the case with a join).

dependencies

Module that defines a dependency injector container.

Auto-wiring is avoided. It should be clear why and when a class is loaded.

create_database(c)

Create the database dependency.

create_event_bus(c)

Create the event bus dependency.

create_mailer(c)

Create the mailer dependency.

create_redis(c)

Create the redis dependency.

domain

Package for all common domain modules.

entity

Module that defines a generic entity.

Entity

Bases: Generic[T]

A base class for an entity.

id: T property

Return the id of the entity.

has_id()

Check if this entity has a valid id.

Returns:

Name Type Description
bool bool

True when the id is not empty.

replace(entity, **changes) classmethod

Return a new entity from the existing entity.

Parameters:

Name Type Description Default
entity(Entity[T])

The entity to copy the values from

required
changes

the values to override when creating the new entity.

{}

Use the same keyword arguments as used on the class constructor (init) to replace the existing value of an attribute. The class constructor will be called to create this new entity. The arguments of the constructor that are not passed in "changes", will get the value from the current entity.

Note

To make it clear that the attributes of an entity are private, they are prefixed with an underscore. The name of the keyword argument does not contain this underscore. This method will try to find the attribute first without underscore. When no attribute exists with that name, it will try to find it with an underscore. When an argument of the constructor contains an underscore as suffix (to avoid naming conflicts for example), the underscore will be removed to find the attribute of the class.

exceptions

Module that defines domain exceptions.

UnprocessableException

Bases: Exception

Raised when a process can't be executed due to the state of the domain.

mailer_service

Module that defines an interface for a service that uses a mailer.

MailerService

Interface for a mailer service.

send() abstractmethod

Send the mail.

repository

Package for all modules related to repositories.

query

Module that defines an interface for a query.

Query

Interface for a query.

count() abstractmethod async

Get the numbers of rows to be returned.

fetch(limit=None, offset=None) abstractmethod

Fetch all rows.

A generator should be returned to avoid reading all rows at once.

fetch_one() abstractmethod async

Fetch just one row.

use_case

Module for defining common classes, functions, ... for use cases.

UseCaseBrowseResult

Bases: NamedTuple

A named tuple for a use case that returns a result of browsing entities.

value_objects

Package for all common value objects.

email_address

Module for an email address value object.

EmailAddress dataclass

A value object for an email address.

__post_init__()

Check if the email address is valid.

__str__()

Return the string representation of an email address.

InvalidEmailException

Bases: Exception

Raised when the email address is not valid.

identifier

Module that defines identifiers.

Identifier

Bases: ABC, Generic[T]

Abstract and generic class for an identifier.

value: T property

Return the id.

__eq__(other)

Check the equality of identifiers.

__hash__()

Create a hash for an identifier.

__str__()

Return the string representation of the id.

is_empty() abstractmethod

Return true when the identifier is not set.

IntIdentifier

Bases: Identifier[int]

Class that implements an identifier with an integer.

__repr__()

Return a string representation of the identifier.

is_empty()

Return True when the id equals 0.

local_timestamp

Module that defines a value object for a local timestamp.

LocalTimestamp dataclass

A value object for a timestamp.

The datetime should always be in UTC.

date: date property

Return the date.

day: int property

Return the day.

empty property

Return True when the timestamp is unknown.

hours: int property

Return the hours.

is_past: bool property

Return True when the timestamp in the past.

minutes: int property

Return the minutes.

month: int property

Return the month.

seconds: int property

Return the seconds.

time: time property

Return the date.

year: int property

Return the year.

__str__()

Return a string representation.

Returns:

Type Description
str

A formatted timestamp in format YYYY-MM-DD HH:mm:ss.

str

An empty string will be returned, when no timestamp is available.

add_delta(**kwargs)

Create a new timestamp by adding the delta to the timestamp.

Returns:

Name Type Description
LocalTimestamp LocalTimestamp

A new timestamp with the delta.

create_from_string(date_time, date_format='%Y-%m-%d %H:%M:%S') classmethod

Create a timestamp from a string.

Parameters:

Name Type Description Default
date_time str

The string to convert to a timestamp.

required
date_format str

The format used in the string.

'%Y-%m-%d %H:%M:%S'
create_now() classmethod

Create a timestamp with the current UTC time.

create_with_delta(**kwargs) classmethod

Create a current local timestamp and applies the delta.

name

Module that defines a value object for a name.

Name dataclass

A value object for a name.

__str__()

Return a string representation.

owner

Module that defines a value object for an owner of an entity.

Owner dataclass

A value object for an owner of an entity.

Attributes:

Name Type Description
id IntIdentifier

The id of the owner (user)

uuid UniqueId

The unique id of the owner (user)

name Name

The name of the owner

password

Module that defines a value object for a password.

Password dataclass

A value object for a password.

__str__()

Return a string representation (hashed password).

create_from_string(password) classmethod

Create a password from a string.

verify(password)

Verify this password against the given password.

period

Module that defines the value object Period.

Period dataclass

Value object for handling a period between dates.

delta: timedelta | None property

Return the delta between end and start time.

endless: bool property

Return True when end date is not set.

__post_init__()

Perform post initialization.

Raises:

Type Description
ValueError

when the start date is before the end date.

create_from_delta(start_date=None, **kwargs) classmethod

Create a period from a delta.

text

Module that defines a value object for text content.

LocaleText dataclass

Value object for the content of a news story.

Attributes:

Name Type Description
locale str

The locale of the content.

format str

The format of the content.

title str

The title of the content.

content str

The long text of the content.

summary str

The summary of the content.

author Owner

The author of the content.

traceable_time TraceableTime

The creation and modification timestamp of the content.

Text

A value object containing content in several locales.

This class is immutable. A new Text instance will be created and returned when content is added, changed or removed.

__init__(content=None)

Initialize the text value object with content.

Parameters:

Name Type Description Default
content dict[str, LocaleText]

A dictionary with content and locale as key.

None
add_translation(content)

Add a new translation.

Parameters:

Name Type Description Default
content LocaleText

The translated content.

required

Returns:

Type Description
Text

A new Text value object that also contains the translated content.

Raises:

Type Description
KeyError

when a translation already existed.

contains_translation(locale)

Check if the given locale is available as translation.

Returns:

Type Description
bool

True when the translation is available.

get_translation(locale)

Get a translation.

Parameters:

Name Type Description Default
locale str

The locale of the content

required

Returns:

Type Description
LocaleText

The content, when available.

remove_translation(content)

Remove a translation.

Parameters:

Name Type Description Default
content LocaleText

The content to remove.

required

Returns:

Type Description
Text

A new Text value object that also contains the rest of the translated

Text

content.

Raises:

Type Description
KeyError

when the translation does not exist.

replace_translation(content)

Replace a translation.

Parameters:

Name Type Description Default
content LocaleText

The content to remove.

required

Returns:

Type Description

A new Text value object that also contains the rest of the translated

content.

Raises:

Type Description
KeyError

when the translation does not exist.

time_period

Module that defines a period between times.

TimePeriod dataclass

A period between two times.

delta: timedelta | None property

Return the delta between end and start time.

When there is no end time, the result will be None.

endless: bool property

Return True when the period does not have an end time.

__post_init__()

Perform post initialization.

Raises:

Type Description
ValueError

when the start time is before the end time.

traceable_time

Module that defines a value object to trace creation/update time of an entity.

TraceableTime dataclass

A value object to track creation/update time.

is_updated property

Check if this entity has been updated.

mark_for_update()

Set the update time to the current time.

unique_id

Module that defines a value object for a unique id.

UniqueId dataclass

A value object for a unique id.

__eq__(other)

Check if a unique id equals the given id.

__str__()

Return a string representation.

create_from_string(uuid_str) classmethod

Create a unique id from te string.

generate() classmethod

Create a new unique id (UUID4).

weekday

Module for defining a value object for a weekday.

Weekday

Bases: Enum

Represent a day in the week.

create_from_date(date) classmethod

Create a Weekday from a date.

Parameters:

Name Type Description Default
date datetime

The date to extract the weekday from.

required

events

Package for all modules related to events.

bus

Module that defines the interface for a bus.

Bus

Interface for a message bus.

publish(event) abstractmethod async

Publish an event.

subscribe(event, task) abstractmethod

Subscribe on an event.

consumer

Module that implements a consumer for a redis stream.

RedisConsumer

A consumer for a Redis stream.

Attributes:

Name Type Description
_stream

The stream to consume.

_group_name

The name of the group.

_callback

The callback to call when a message is consumed.

_is_stopping

An event to stop the consumer.

cancel()

Cancel the consumer.

consume(consumer_name, check_backlog=True) async

Consume messages from a stream.

Parameters:

Name Type Description Default
consumer_name str

The name of the consumer.

required
check_backlog bool

When True, all pending messages will be processed first.

True
event

Module that defines the base class Event.

Event dataclass

Base class for all events.

data: dict property

Returns a dict that can be used to serialize the event.

EventMeta dataclass

Metadata for the event.

redis_bus

Define a message bus using Redis.

RedisBus

Bases: Bus

A message bus using Redis streams.

The name of the event is mostly ... Each module will have its own stream.

cancel() async

Cancel all consumers.

publish(event) async

Publish the event.

The event will be placed on the stream that belongs to the module.

run() async

Start all consumers.

For each stream a consumer will be started. This method will wait for all tasks to end.

subscribe(event, task)

Subscribe a callback to an event.

When an event is retrieved from a stream, the callback will be executed. For each stream, a consumer will be started when the bus is running.

stream

Define a Redis stream.

RedisGroupInfo dataclass

Dataclass with information about a redis stream group.

RedisMessage dataclass

Dataclass for a message on a stream.

create_from_redis(messages) classmethod

Create a RedisMessage from messages retrieved from a Redis stream.

RedisMessageException

Bases: Exception

Exception raised when the message is not a RedisMessage.

message_id: str property

Return the message id of the message that raised this exception.

stream_name: str property

Return the stream of the message.

__str__()

Return a string representation of this exception.

RedisStream

A stream using Redis.

Attributes:

Name Type Description
_redis

Redis connection.

_stream_name

Name of the Redis stream.

A stream will be created when a first group is created or when a first message is added.

name: str property

Return the name of the stream.

ack(group_name, id_) async

Acknowledge the message with the given id for the given group.

Parameters:

Name Type Description Default
group_name str

The name of the group.

required
id_ str

The id of the message to acknowledge.

required
add(message) async

Add a new message to the stream.

Parameters:

Name Type Description Default
message RedisMessage

The message to add to the stream.

required

Returns:

Type Description
RedisMessage

The original message. When the id of the message was a *, the id returned

RedisMessage

from redis will be set.

The data will be serialized to JSON. The field 'data' will be used to store this JSON.

consume(group_name, consumer_name, id_='>', block=None) async

Consume a message from a stream.

Parameters:

Name Type Description Default
group_name str

Name of the group.

required
consumer_name str

Name of the consumer.

required
id_

The id to start from (default is >)

'>'
block int | None

milliseconds to wait for an entry. Use None to not block.

None
create_group(group_name, id_='$') async

Create a group (if it doesn't exist yet).

Parameters:

Name Type Description Default
group_name str

The name of the group

required
id_

The id used as starting id. Default is $, which means only new messages.

'$'

Returns:

Type Description
bool

True, when the group is created, False when the group already exists.

When the stream does not exist yet, it will be created.

delete() async

Delete the stream.

Returns:

Type Description
bool

True when the stream is deleted. False when the stream didn't exist or

bool

isn't deleted.

delete_entries(*ids) async

Delete entries from the stream.

Returns the number of deleted entries.

first_entry_id() async

Return the id of the first entry.

An empty string will be returned when there is no entry on the stream.

get_group(group_name) async

Get the information about a group.

Returns:

Type Description
RedisGroupInfo | None

RedisGroup when the group exist, otherwise None is returned.

get_groups() async

Get all groups of the stream.

Returns:

Type Description
dict[str, RedisGroupInfo]

A list of groups.

info() async

Return information about the stream.

Returns:

Type Description
RedisStreamInfo | None

A tuple with length, first-entry-id and last-entry-id. None is returned

RedisStreamInfo | None

when the stream does not exist.

last_entry_id() async

Return the id of the last entry.

An empty string will be returned when there is no entry on the stream.

length() async

Return the number of entries on the stream.

0 will be returned when the stream does not exist.

read(last_id='$', block=None) async

Read an entry from the stream.

Parameters:

Name Type Description Default
last_id str

only entries with an id greater than this id will be returned. The default is $, which means to return only new entries.

'$'
block int | None

milliseconds to wait for an entry. Use None to not block.

None

Returns:

Type Description
RedisMessage | None

None when no entry is read. A tuple with the id and data of the entry

RedisMessage | None

when an entry is read.

RedisStreamInfo dataclass

Dataclass with information about a redis stream.

json_api

Module that defines some jsonapi related models.

Attribute dataclass

Dataclass for storing information about attributes.

__post_init__()

Set the optional field.

DocumentBaseModel

Bases: BaseModel

A basemodel for a document.

dict(*args, **kwargs)

Overloads dict to remove 'meta' when it's None.

Meta

Bases: BaseModel

Defines the metadata for the document model.

Attributes:

Name Type Description
count int | None

The number of actual resources

offset int | None

The offset of the returned resources (pagination)

limit int | None

The maximum number of returned resources (pagination)

A limit of 0, means there was no limit was set.

Config

Allow extra attributes on the Meta object.

PaginationModel

Bases: BaseModel

A model for pagination query parameters.

Use this as a dependency on a route. This will handle the page[offset] and page[limit] query parameters.

Attributes:

Name Type Description
offset int | None

The value of the page[offset] query parameter. Default is None.

limit int | None

The value of the page[limit] query parameter. Default is None.

Relationship dataclass

Dataclass for storing information about relationships.

__post_init__()

Initialise the properties that depend on the type.

Resource

A class that is responsible for generating all the models needed for JSON:API.

Use the resource decorator to mark a class as a JSON:API resource. The decorator will attach an instance of this class to the marked class.

__str__()

Use type as string representation.

build(auto=True)

Build the JSONAPI resource models.

get_attribute(attribute_name)

Return the attribute definition for the given name.

None is returned, when the attribute does not exist.

get_document_model()

Get the document model.

get_model_class_prefix()

Return the prefix used for creating the model classes.

The prefix is the name of the class without the "Resource" suffix.

get_relationship(relationship_name)

Return the relationship definition for the given name.

None is returned, when the relationship does not exist.

get_resource_attribute(attribute_name, resource_instance)

Return the value of the attribute from the resource.

The getter created when scanning the class for the attributes will be used to retrieve the attribute value from the resource.

get_resource_attributes(resource_instance)

Get all attribute values from the resource instance.

get_resource_data_model()

Get the resource model with data as object.

get_resource_data_model_list()

Get resource model with data as list.

get_resource_id(resource_instance)

Return the id of the resource.

The getter created when scanning the class for the id property/method will be used to retrieve the id from the resource.

get_resource_identifier(resource_instance)

Get an instance of the resource identifier.

A resource identifier contains the id and the type of the resource.

get_resource_identifier_model()

Return the resource identifier model.

The resource identifier model contains the id and type of the resource.

get_resource_model()

Get the resource model.

The resource model contains the id, type, attributes and relationships of the resource.

get_resource_object(resource_instance)

Get the resource from the resource instance.

It returns a tuple. The first value will contain the resource object, while the second value will contain a list of the related resource objects.

get_resource_relationships(resource_instance)

Get all relationship values from the resource instance.

get_type()

Get the resource type.

has_id()

Check if there is an id available in the resource.

serialize(resource_instance)

Serialize the resource instance into a document model.

serialize_list(resource_instances)

Serialize a list of resources into a document model.

attribute(_func=None, *, name=None)

Turn a method into an attribute of a resource with this decorator.

When name is omitted, the name of the method is used. Brackets can be omitted when no name is passed.

id(_func=None)

Mark this method as the way to get the id of the resource with this decorator.

Brackets can be omitted.

relationship(_func=None, *, name=None)

Turn a method into a relationship of a resource with this decorator.

When name is omitted, the name of the method is used. Brackets can be omitted when no name is passed.

resource(type_, auto=True)

Turn a class into a JSONAPI resource with this decorator.

mail

Package for all modules related to mailing.

mail

Module that implements the Message interface for a mail.

Mail

Bases: Message

Implements a text/html mail message.

headers: dict[str, str] property

Return the headers.

html: str | None property

Return the HTML content.

recipients: Recipients property

Return the recipients.

subject: str property

Return the subject of the mail.

text: str | None property

Return the text content.

with_headers(headers)

Clone the current mail and set the headers.

with_html(html)

Clone the current mail and set the HTML content.

with_recipients(recipients)

Clone the current mail and set the recipients.

with_subject(subject)

Clone the current mail and set the subject.

with_text(text)

Clone the current mail and set the text content.

mailer

Module that defines an interface for a mail service.

Mailer

Bases: ABC

Interface for a mail service.

send(message) abstractmethod

Send the message.

MailerException

Bases: Exception

Exception raised from a Mailer.

message

Module that defines an interface for a mail message.

Message

Interface for an immutable message.

headers: dict[str, str] abstractmethod property

Returns the headers for this message.

html: str | None abstractmethod property

Returns the HTML for the message.

recipients: Recipients abstractmethod property

Returns the recipients for the message.

subject: str abstractmethod property

Return the subject of the message.

text: str | None abstractmethod property

Return the text for the message.

with_headers(headers) abstractmethod

Set the headers for the message.

This method must return a new Message instance.

with_html(html) abstractmethod

Set the HTML for the message.

This method must return a new Message instance.

with_recipients(recipients) abstractmethod

Set the recipients for the message.

This method must return a new Message instance.

with_subject(subject) abstractmethod

Set the subject for the message.

This method must return a new Message instance.

with_text(text) abstractmethod

Set the text for the message.

This method must return a new Message instance.

recipient

Module that defines a recipient.

Recipient dataclass

Defines a recipient.

Recipients dataclass

Defines all recipients for an email.

All methods are immutable.

add_bcc(*bcc)

Clone the recipients and add a blind copy recipient.

add_cc(*cc)

Clone the recipients and add a copy recipient.

add_to(*to)

Clone the recipients and add a receiver.

with_bcc(*bcc)

Clone the recipients and set the blind copy recipient.

with_cc(*cc)

Clone the recipients and set the copy recipient.

with_from(from_)

Clone the recipients and set the sender.

with_to(*to)

Clone the recipients and set the receiver(s).

smtp_mailer

Module that defines a mailer service with SMTP.

SmtpMailer

Bases: Mailer

A mailer service that uses an SMTP server.

__del__()

Disconnect from the mailer.

connect()

Connect to the SMTP server.

disconnect()

Disconnect from the SMTP server.

login(user, password)

Login to the SMTP server.

send(message)

Send a message to the SMTP server.

security

Package for all security modules.

settings

Module for the settings of this application.

CORSSettings

Bases: BaseModel

Settings for configuring CORS.

DatabaseSettings

Bases: BaseModel

Settings for the database connection.

EmailSettings

Bases: BaseModel

Settings for sending emails.

LoggerSettings

Bases: BaseModel

Settings for the logger.

RedisSettings

Bases: BaseModel

Settings for redis.

SecuritySettings

Bases: BaseModel

Setting or security.

Settings

Bases: BaseModel

Class with settings.

SettingsException

Bases: Exception

Raised when a problem occurred while loading the settings.

TemplateSettings

Bases: BaseModel

Settings for template.

WebsiteSettings

Bases: BaseModel

Settings about the website.

get_settings()

Dependency function for creating the Settings instance.

The settings are cached with lru_cache, which means the file is only loaded ounce.

:raises: core.settings.SettingsException: Raised when the env variable is not set, or when the file can't be read.

template

Package for all template modules.

dependency

Module that defines a dependency for a template engine.

get_template_engine(settings=Depends(get_settings))

Get the template engine.

jinja2_engine

Modules that implements the template engine interface for jinja2.

Jinja2Engine

Bases: TemplateEngine

Implements the TemplateEngine interface for Jinja2.

__init__(template_path, **kwargs)

Construct a Jinja2Engine.

kwargs will be merged to the variables that are used to render a template. Use it for variables that are used in all templates.

create(template_file_path, lang='nl')

Create a jinja2 template.

jinja2_template

Module that implements the Template interface for a jinja2 template.

Jinja2Template

Bases: Template

A jinja2 template.

__init__(template, **kwargs)

Construct a new template.

kwargs will be merged with the variables used in render.

render(**kwargs)

Render the template.

mail_template

Module that defines a template for creating HTML/Text mails.

MailTemplate

Defines a wrapper around template to generate an HTML and text mail.

create_mail(recipients, subject, **kwargs)

Create the mail with HTML and text template.

render_html(**kwargs)

Render the HTML template.

render_text(**kwargs)

Render the text template.

template

Module that defines an interface for a template.

Template

Interface for a template.

render(**kwargs) abstractmethod

Render the template with the variables.

template_engine

Module that defines an interface for a template engine.

TemplateEngine

Interface for a template engine.

create(template_file_path, lang='nl') abstractmethod

Create a template from the given file path.

When the template cannot be found, a TemplateNotFoundException should be raised.

TemplateNotFoundException

Bases: Exception

Raised when a template cannot be found.

kwai_api

Module for starting the api server.

create_args()

Parse and create cli arguments.

kwai_bus

Entry point for starting the event bus.

create_bus()

Create the event bus.

kwai_cli

Module that starts the CLI for kwai.

modules

Package for all modules.

identity

The identity module is responsible for user management.

kwai.modules.identity.authenticate_user

Module that implements the use case: authenticate user.

AuthenticateUser

Use case to authenticate a user.

Attributes:

Name Type Description
_user_account_repo UserAccountRepository

The repository for getting the user account.

_access_token_repo UserAccountRepository

The repository for creating the access token.

_refresh_token_repo UserAccountRepository

The repository for creating the refresh token.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command AuthenticateUserCommand

The input for this use case.

required

Returns:

Name Type Description
RefreshTokenEntity RefreshTokenEntity

On success, a refresh token entity will be returned.

Raises:

Type Description
InvalidEmailException

Raised when the username contains an invalid email address.

UserAccountNotFoundException

Raised when the user with the given email address doesn't exist.

AuthenticateUserCommand dataclass

Input for the (AuthenticateUser) use case.

Attributes:

Name Type Description
username str

The email address of the user.

password str

The password of the user.

access_token_expiry_minutes int

Minutes before expiring the access token. Default is 2 hours.

refresh_token_expiry_minutes int

Minutes before expiring the refresh token. Default is 2 months.

kwai.modules.identity.create_user

Use case: create a user.

CreateUser

Use case for creating a new user.

__init__(user_account_repo)

Create the use case.

Parameters:

Name Type Description Default
user_account_repo UserAccountRepository

Repository that creates a new user account.

required

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command CreateUserCommand

The input for this use case.

required

Returns:

Type Description
UserAccountEntity

An entity for a user account.

Raises:

Type Description
UnprocessableException

when the email address is already used by another user.

CreateUserCommand dataclass

Input for the CreateUser use case.

See: CreateUser

Attributes:

Name Type Description
email str

The email address for the new user.

first_name str

The first name of the new user.

last_name str

The last name of the new user.

password str

The password for the new user.

remark str

A remark about the new user.

kwai.modules.identity.delete_user_invitation

Implement the use case: delete a user invitation.

DeleteUserInvitation

Implements the use case 'delete a user invitation'.

__init__(user_invitation_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_invitation_repo UserInvitationRepository

A repository for deleting the user invitation.

required

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command DeleteUserInvitationCommand

The input for this use case.

required

Raises:

Type Description
UserInvitationNotFoundException

Raised when then invitation is not found.

DeleteUserInvitationCommand dataclass

Input for the use case.

DeleteUserInvitation

Attributes:

Name Type Description
uuid str

The unique id of the user invitation.

kwai.modules.identity.get_user_invitation

Implement the use case: get a user invitation.

GetUserInvitation

Implements the use case 'get a user invitation'.

__init__(user_invitation_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_invitation_repo UserInvitationRepository

A repository for getting the user invitation.

required

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetUserInvitationCommand

The input for this use case.

required

Returns:

Type Description
UserInvitationEntity

A user invitation entity

Raises:

Type Description
UserInvitationNotFoundException

Raised when then invitation is not found.

GetUserInvitationCommand dataclass

Input for the use case.

GetUserInvitation

Attributes:

Name Type Description
uuid str

The unique id of the user invitation.

kwai.modules.identity.get_invitations

Implement the use case: get user invitations.

GetInvitations

Implementation of the use case.

Use this use case for getting user invitations.

__init__(user_invitation_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_invitation_repo UserInvitationRepository

A repository for getting the user invitations.

required

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetInvitationsCommand

The input for this use case.

required

Returns:

Type Description
tuple[int, AsyncIterator[UserInvitationEntity]]

A tuple with the number of entities and an iterator for invitation entities.

GetInvitationsCommand dataclass

Input for the use case.

GetInvitations

Attributes:

Name Type Description
offset int | None

Offset to use. Default is None.

limit int | None

The max. number of elements to return. Default is None, which means all.

kwai.modules.identity.invite_user

Module for the invite user use case.

InviteUser

Invite user use case.

This use case will try to create an invitation for a user.

__init__(user, user_repo, user_invitation_repo, bus)

Initialize the use case.

Parameters:

Name Type Description Default
user UserEntity

The inviter.

required
user_repo UserRepository

The repository to check if the email address is still free.

required
user_invitation_repo UserInvitationRepository

The repository for creating an invitation.

required
bus Bus

A message bus for publishing the user invitation created event.

required

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command InviteUserCommand

The input for this use case.

required

Returns:

Type Description
UserInvitationEntity

A user invitation

Raises:

Type Description
UnprocessableException

raised when the email address is already in use or when there are still pending invitations for the email address.

InviteUserCommand dataclass

Input for the use case.

InviteUser

Attributes:

Name Type Description
first_name str

Firstname of the invited

last_name str

Lastname of the invited

email str

Email address of the invited

expiration_in_days int

After how many days will the invitation expire?

remark str

A remark about this invitation

kwai.modules.identity.logout

Module that implements the logout use case.

Logout

Use case: logout a user.

A user is logged out by revoking the refresh token. The access token that is related to this refresh token will also be revoked.

Attributes:

Name Type Description
_refresh_token_repository RefreshTokenRepository

The repository to get and update the refresh token.

_access_token_repository AccessTokenRepository

The repository to get and update the access token.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command LogoutCommand

The input for this use case.

required

Raises:

Type Description
RefreshTokenNotFoundException

The refresh token with the identifier could not be found.

LogoutCommand dataclass

Command for the logout use case.

Attributes:

Name Type Description
identifier(str)

The refresh token to revoke

kwai.modules.identity.mail_user_invitation

Module that defines the use case for sending a user invitation email.

MailUserInvitation

Use case for sending a user invitation email.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command MailUserInvitationCommand

the input for this use case.

required

Raises:

Type Description
UserInvitationNotFoundException

Raised when the user invitation cannot be found.

UnprocessableException

Raised when the mail was already sent. Raised when the user recovery was already confirmed.

MailUserInvitationCommand dataclass

Command for the use case MailUserInvitation.

Attributes:

Name Type Description
uuid str

The unique id of the user invitation.

kwai.modules.identity.mail_user_recovery

Module that defines the use case for sending a recovery email.

MailUserRecovery

Use case for sending a recovery email.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command MailUserRecoveryCommand

The input for this use case.

required

Raises:

Type Description
UserRecoveryNotFoundException

Raised when the user recovery cannot be found.

UnprocessableException

Raised when the mail was already sent. Raised when the user recovery was already confirmed.

MailUserRecoveryCommand dataclass

Command for the use case MailUserRecovery.

Attributes:

Name Type Description
uuid str

The unique id of the user recovery.

kwai.modules.identity.recover_user

Module that implements the recover user use case.

RecoverUser

Use case: recover user.

Attributes:

Name Type Description
_user_account_repo UserAccountRepository

The repository for getting the user account.

_user_recovery_repo UserRecoveryRepository

The repository for creating a user recovery.

_event_bus Bus

An event bus for dispatching the UserRecoveryCreatedEvent event.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command RecoverUserCommand

The input for this use case.

required

Raises:

Type Description
UserAccountNotFoundException

Raised when the user with the given email address does not exist.

UnprocessableException

Raised when the user is revoked

RecoverUserCommand dataclass

Command for the recover user use case.

kwai.modules.identity.refresh_access_token

Module that defines the use case for refreshing an access token.

RefreshAccessToken

Use case for refreshing an access token.

Attributes:

Name Type Description
_refresh_token_repo RefreshTokenRepository

The repo for getting and creating a new refresh token.

_access_token_repo AccessTokenRepository

The repo for updating and creating an access token.

Note

A new access token will also result in a new refresh token.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command RefreshAccessTokenCommand

The input for this use case.

required

Raises:

Type Description
RefreshTokenNotFoundException

Raised when the refresh token does not exist.

AuthenticationException

Raised when the refresh token is expired, the refresh token is revoked or the user is revoked.

RefreshAccessTokenCommand dataclass

Input for the refresh access token use case.

Attributes:

Name Type Description
identifier str

The identifier of the refresh token.

access_token_expiry_minutes int

Minutes before expiring the access token. Default is 2 hours.

refresh_token_expiry_minutes int

Minutes before expiring the refresh token. Default is 2 months.

kwai.modules.identity.reset_password

Module that implements the reset password use case.

ResetPassword

Reset password use case.

This use case will try to reset the password of a user. A user can reset the password with a unique id. This unique id is linked to a user recovery.

__init__(user_account_repo, user_recovery_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_account_repo UserAccountRepository

The repository for getting the user account.

required
user_recovery_repo UserRecoveryRepository

The repository for getting and updating the user recovery.

required

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command ResetPasswordCommand

The input for this use case.

required

Raises:

Type Description
UserRecoveryNotFoundException

Raised when the user recovery with the given uuid does not exist.

UserRecoveryExpiredException

Raised when the user recovery is expired.

UserRecoveryConfirmedException

Raised when the user recovery is already used.

UserAccountNotFoundException

Raised when the user with the email address that belongs to the user recovery, does not exist.

NotAllowedException

Raised when the user is revoked.

ResetPasswordCommand dataclass

Command for the reset password use case.

Attributes:

Name Type Description
uuid str

The unique id of the user recovery

password str

The new password.

UserRecoveryConfirmedException

Bases: Exception

Raised when the user recovery was already used.

UserRecoveryExpiredException

Bases: Exception

Raised when the user recovery is expired.

authenticate_user

Module that implements the use case: authenticate user.

AuthenticateUser

Use case to authenticate a user.

Attributes:

Name Type Description
_user_account_repo UserAccountRepository

The repository for getting the user account.

_access_token_repo UserAccountRepository

The repository for creating the access token.

_refresh_token_repo UserAccountRepository

The repository for creating the refresh token.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command AuthenticateUserCommand

The input for this use case.

required

Returns:

Name Type Description
RefreshTokenEntity RefreshTokenEntity

On success, a refresh token entity will be returned.

Raises:

Type Description
InvalidEmailException

Raised when the username contains an invalid email address.

UserAccountNotFoundException

Raised when the user with the given email address doesn't exist.

AuthenticateUserCommand dataclass

Input for the (AuthenticateUser) use case.

Attributes:

Name Type Description
username str

The email address of the user.

password str

The password of the user.

access_token_expiry_minutes int

Minutes before expiring the access token. Default is 2 hours.

refresh_token_expiry_minutes int

Minutes before expiring the refresh token. Default is 2 months.

create_user

Use case: create a user.

CreateUser

Use case for creating a new user.

__init__(user_account_repo)

Create the use case.

Parameters:

Name Type Description Default
user_account_repo UserAccountRepository

Repository that creates a new user account.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command CreateUserCommand

The input for this use case.

required

Returns:

Type Description
UserAccountEntity

An entity for a user account.

Raises:

Type Description
UnprocessableException

when the email address is already used by another user.

CreateUserCommand dataclass

Input for the CreateUser use case.

See: CreateUser

Attributes:

Name Type Description
email str

The email address for the new user.

first_name str

The first name of the new user.

last_name str

The last name of the new user.

password str

The password for the new user.

remark str

A remark about the new user.

delete_user_invitation

Implement the use case: delete a user invitation.

DeleteUserInvitation

Implements the use case 'delete a user invitation'.

__init__(user_invitation_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_invitation_repo UserInvitationRepository

A repository for deleting the user invitation.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command DeleteUserInvitationCommand

The input for this use case.

required

Raises:

Type Description
UserInvitationNotFoundException

Raised when then invitation is not found.

DeleteUserInvitationCommand dataclass

Input for the use case.

DeleteUserInvitation

Attributes:

Name Type Description
uuid str

The unique id of the user invitation.

exceptions

Module that defines common identity exceptions.

AuthenticationException

Bases: Exception

Raised when authentication is not allowed.

NotAllowedException

Bases: Exception

Raised when an action is not allowed.

get_invitations

Implement the use case: get user invitations.

GetInvitations

Implementation of the use case.

Use this use case for getting user invitations.

__init__(user_invitation_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_invitation_repo UserInvitationRepository

A repository for getting the user invitations.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetInvitationsCommand

The input for this use case.

required

Returns:

Type Description
tuple[int, AsyncIterator[UserInvitationEntity]]

A tuple with the number of entities and an iterator for invitation entities.

GetInvitationsCommand dataclass

Input for the use case.

GetInvitations

Attributes:

Name Type Description
offset int | None

Offset to use. Default is None.

limit int | None

The max. number of elements to return. Default is None, which means all.

get_user_invitation

Implement the use case: get a user invitation.

GetUserInvitation

Implements the use case 'get a user invitation'.

__init__(user_invitation_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_invitation_repo UserInvitationRepository

A repository for getting the user invitation.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetUserInvitationCommand

The input for this use case.

required

Returns:

Type Description
UserInvitationEntity

A user invitation entity

Raises:

Type Description
UserInvitationNotFoundException

Raised when then invitation is not found.

GetUserInvitationCommand dataclass

Input for the use case.

GetUserInvitation

Attributes:

Name Type Description
uuid str

The unique id of the user invitation.

invite_user

Module for the invite user use case.

InviteUser

Invite user use case.

This use case will try to create an invitation for a user.

__init__(user, user_repo, user_invitation_repo, bus)

Initialize the use case.

Parameters:

Name Type Description Default
user UserEntity

The inviter.

required
user_repo UserRepository

The repository to check if the email address is still free.

required
user_invitation_repo UserInvitationRepository

The repository for creating an invitation.

required
bus Bus

A message bus for publishing the user invitation created event.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command InviteUserCommand

The input for this use case.

required

Returns:

Type Description
UserInvitationEntity

A user invitation

Raises:

Type Description
UnprocessableException

raised when the email address is already in use or when there are still pending invitations for the email address.

InviteUserCommand dataclass

Input for the use case.

InviteUser

Attributes:

Name Type Description
first_name str

Firstname of the invited

last_name str

Lastname of the invited

email str

Email address of the invited

expiration_in_days int

After how many days will the invitation expire?

remark str

A remark about this invitation

logout

Module that implements the logout use case.

Logout

Use case: logout a user.

A user is logged out by revoking the refresh token. The access token that is related to this refresh token will also be revoked.

Attributes:

Name Type Description
_refresh_token_repository RefreshTokenRepository

The repository to get and update the refresh token.

_access_token_repository AccessTokenRepository

The repository to get and update the access token.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command LogoutCommand

The input for this use case.

required

Raises:

Type Description
RefreshTokenNotFoundException

The refresh token with the identifier could not be found.

LogoutCommand dataclass

Command for the logout use case.

Attributes:

Name Type Description
identifier(str)

The refresh token to revoke

mail_user_invitation

Module that defines the use case for sending a user invitation email.

MailUserInvitation

Use case for sending a user invitation email.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command MailUserInvitationCommand

the input for this use case.

required

Raises:

Type Description
UserInvitationNotFoundException

Raised when the user invitation cannot be found.

UnprocessableException

Raised when the mail was already sent. Raised when the user recovery was already confirmed.

MailUserInvitationCommand dataclass

Command for the use case MailUserInvitation.

Attributes:

Name Type Description
uuid str

The unique id of the user invitation.

mail_user_recovery

Module that defines the use case for sending a recovery email.

MailUserRecovery

Use case for sending a recovery email.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command MailUserRecoveryCommand

The input for this use case.

required

Raises:

Type Description
UserRecoveryNotFoundException

Raised when the user recovery cannot be found.

UnprocessableException

Raised when the mail was already sent. Raised when the user recovery was already confirmed.

MailUserRecoveryCommand dataclass

Command for the use case MailUserRecovery.

Attributes:

Name Type Description
uuid str

The unique id of the user recovery.

recover_user

Module that implements the recover user use case.

RecoverUser

Use case: recover user.

Attributes:

Name Type Description
_user_account_repo UserAccountRepository

The repository for getting the user account.

_user_recovery_repo UserRecoveryRepository

The repository for creating a user recovery.

_event_bus Bus

An event bus for dispatching the UserRecoveryCreatedEvent event.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command RecoverUserCommand

The input for this use case.

required

Raises:

Type Description
UserAccountNotFoundException

Raised when the user with the given email address does not exist.

UnprocessableException

Raised when the user is revoked

RecoverUserCommand dataclass

Command for the recover user use case.

refresh_access_token

Module that defines the use case for refreshing an access token.

RefreshAccessToken

Use case for refreshing an access token.

Attributes:

Name Type Description
_refresh_token_repo RefreshTokenRepository

The repo for getting and creating a new refresh token.

_access_token_repo AccessTokenRepository

The repo for updating and creating an access token.

Note

A new access token will also result in a new refresh token.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command RefreshAccessTokenCommand

The input for this use case.

required

Raises:

Type Description
RefreshTokenNotFoundException

Raised when the refresh token does not exist.

AuthenticationException

Raised when the refresh token is expired, the refresh token is revoked or the user is revoked.

RefreshAccessTokenCommand dataclass

Input for the refresh access token use case.

Attributes:

Name Type Description
identifier str

The identifier of the refresh token.

access_token_expiry_minutes int

Minutes before expiring the access token. Default is 2 hours.

refresh_token_expiry_minutes int

Minutes before expiring the refresh token. Default is 2 months.

reset_password

Module that implements the reset password use case.

ResetPassword

Reset password use case.

This use case will try to reset the password of a user. A user can reset the password with a unique id. This unique id is linked to a user recovery.

__init__(user_account_repo, user_recovery_repo)

Initialize the use case.

Parameters:

Name Type Description Default
user_account_repo UserAccountRepository

The repository for getting the user account.

required
user_recovery_repo UserRecoveryRepository

The repository for getting and updating the user recovery.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command ResetPasswordCommand

The input for this use case.

required

Raises:

Type Description
UserRecoveryNotFoundException

Raised when the user recovery with the given uuid does not exist.

UserRecoveryExpiredException

Raised when the user recovery is expired.

UserRecoveryConfirmedException

Raised when the user recovery is already used.

UserAccountNotFoundException

Raised when the user with the email address that belongs to the user recovery, does not exist.

NotAllowedException

Raised when the user is revoked.

ResetPasswordCommand dataclass

Command for the reset password use case.

Attributes:

Name Type Description
uuid str

The unique id of the user recovery

password str

The new password.

UserRecoveryConfirmedException

Bases: Exception

Raised when the user recovery was already used.

UserRecoveryExpiredException

Bases: Exception

Raised when the user recovery is expired.

tasks

Module that lists all tasks of the identity module.

tokens

Package for all modules related to tokens.

access_token

Module that defines an access token entity.

AccessTokenEntity

Bases: Entity[AccessTokenIdentifier]

An access token entity.

expiration: datetime property

Return the expiration timestamp of the access token.

expired: bool property

Return true when the access token is expired.

identifier: TokenIdentifier property

Return the identifier of the access token.

revoked: bool property

Return True when the access token is revoked.

traceable_time: TraceableTime property

Return the creation/modification timestamps.

user_account: UserAccountEntity property

Return the user of this access token.

revoke()

Revoke the access token.

access_token_db_query

Module that implements an access token query for a database.

AccessTokenDbQuery

Bases: AccessTokenQuery, DatabaseQuery

An access token query for a database.

columns property

Return the columns for the query.

filter_by_id(id_)

Add a filter for id.

filter_by_token_identifier(identifier)

Add a filter for a token identifier.

init()

Initialize the query.

access_token_db_repository

Module that implements an access token repository for a database.

AccessTokenDbRepository

Bases: AccessTokenRepository

Database repository for the access token entity.

access_token_query

Module that defines an interface for an access token query.

AccessTokenQuery

Bases: Query

An interface for querying an access token.

filter_by_id(id_) abstractmethod

Filter for the given id.

filter_by_token_identifier(identifier) abstractmethod

Filter for the given token identifier.

access_token_repository

Module that defines an interface for an access token repository.

AccessTokenNotFoundException

Bases: Exception

Raised when the access token could not be found.

AccessTokenRepository

Interface for an access token repository.

create(access_token) abstractmethod async

Save a new access token.

create_query() abstractmethod

Create a query for a access token.

get(id_) abstractmethod async

Get the access token with the given id.

get_all(query=None, limit=None, offset=None) abstractmethod async

Get all access token.

get_by_identifier(identifier) abstractmethod async

Get the access token with the given identifier.

update(access_token) abstractmethod async

Update the access token.

refresh_token

Module for a refresh token entity.

RefreshTokenEntity

Bases: Entity[RefreshTokenIdentifier]

A refresh token entity.

access_token: AccessTokenEntity property

Return the associated access token.

expiration: datetime property

Return the expiration timestamp of the refresh token.

expired: bool property

Return True when the token is expired.

identifier: TokenIdentifier property

Return the identifier of the refresh token.

revoked: bool property

Return True when the refresh token is revoked.

traceable_time: TraceableTime property

Return the creation/modification timestamps.

revoke()

Revoke the refresh token.

refresh_token_db_query

Module that implements a refresh token query for a database.

RefreshTokenDbQuery

Bases: RefreshTokenQuery, DatabaseQuery

A refresh token query for a database.

refresh_token_db_repository

Module that implements a refresh token repository for a database.

RefreshTokenDbRepository

Bases: RefreshTokenRepository

Database repository for the refresh token entity.

refresh_token_query

Module that defines an interface for querying a refresh token.

RefreshTokenQuery

Bases: Query

An interface for querying a refresh token.

filter_by_id(id_) abstractmethod

Filter for the given id.

filter_by_token_identifier(identifier) abstractmethod

Filter for the given token identifier.

refresh_token_repository

Module that defines an interface for a refresh token repository.

RefreshTokenNotFoundException

Bases: Exception

Raised when the refresh token can't be found.

RefreshTokenRepository

Interface for a refresh token repository.

create(refresh_token) abstractmethod async

Save a new refresh token.

create_query() abstractmethod

Create a query for a refresh token.

get(id_) abstractmethod async

Get the refresh token entity with the given id.

get_all(query=None, limit=None, offset=None) abstractmethod async

Get all refresh tokens.

get_by_token_identifier(identifier) abstractmethod async

Get the refresh token with the given token identifier.

update(refresh_token) abstractmethod async

Update the refresh token.

token_identifier

Module that defines a value object for a token identifier.

TokenIdentifier dataclass

A value object for a token identifier.

__str__()

Return a string representation of the token.

generate() classmethod

Create a new token identifier with a random text string.

token_tables

Module that defines all tables for tokens.

AccessTokenRow dataclass

Represent a table row in the access tokens table.

create_entity(user_account)

Create an entity from the table row.

persist(access_token) classmethod

Persist an access token entity to a table record.

RefreshTokenRow dataclass

Represent a table row in the refresh token table.

create_entity(access_token)

Create a refresh token entity from the table row.

persist(refresh_token) classmethod

Transform a refresh token entity into a table record.

user_invitations

Package that defines modules for user invitations.

user_invitation

Module that defines a user invitation entity.

UserInvitationEntity

Bases: Entity[UserInvitationIdentifier]

A user invitation entity.

A user invitation is a request to someone to become a member of the site.

confirmed: bool property

Return True when the invitation was confirmed.

confirmed_at: LocalTimestamp property

Return when this invitation was used.

email: EmailAddress property

Return the email address that receives this invitation.

expired_at: LocalTimestamp property

Return when the invitation will expire.

is_expired: bool property

Return True when the invitation is expired.

mailed: bool property

Return True if the email has already been sent.

mailed_at: LocalTimestamp property

Return the timestamp of sending the email.

name: Name property

Return the name of the person that receives this invitation.

remark: str property

Return the remark about the invitation.

revoked: bool property

Is this invitation revoked?.

traceable_time: TraceableTime property

Return the creation/modification timestamp of this invitation.

user: UserEntity property

Return the user that created this invitation.

uuid: UniqueId property

Return the unique id of this invitation.

__init__(*, id_=None, email, name, uuid=None, expired_at=None, remark='', mailed_at=None, user, confirmed_at=None, revoked=False, traceable_time=None)

Construct a user invitation.

Parameters:

Name Type Description Default
id_ UserInvitationIdentifier | None

The id of the user invitation.

None
email EmailAddress

The email address that receives the invitation.

required
name Name

The name of the invited

required
uuid UniqueId | None

The unique id to use to validate this invitation.

None
expired_at LocalTimestamp | None

The timestamp when the invitation expires.

None
remark str

A remark about the invitation.

''
mailed_at LocalTimestamp | None

The timestamp of sending out the email.

None
user UserEntity

The user that created the invitation.

required
confirmed_at LocalTimestamp | None

The timestamp when the invitation was used.

None
revoked bool

Is this invitation revoked?

False
traceable_time TraceableTime | None

The creation/modification timestamp of the invitation.

None
confirm()

Confirm the invitation, the invitation was used to create a new user.

mail_sent()

Set the timestamp when the mail has been sent.

user_invitation_db_query

Module that implements a UserInvitationQuery for a database.

UserInvitationDbQuery

Bases: UserInvitationQuery, DatabaseQuery

A database query for a user invitation.

user_invitation_db_repository

Module that implements a user invitation repository for a database.

UserInvitationDbRepository

Bases: UserInvitationRepository

A user invitation repository for a database.

Attributes:

Name Type Description
_database(Database)

the database for this repository.

user_invitation_events

Module that defines all user invitation events.

UserInvitationCreatedEvent dataclass

Bases: Event

Event raised when a user invitation is created.

user_invitation_mailer

Module that defines a mailer for a user invitation.

UserInvitationMailer

Bases: MailerService

Send a user invitation mail.

user_invitation_query

Module that defines an interface for a user invitation query.

UserInvitationQuery

Bases: Query, ABC

An interface for querying user invitations.

filter_active(timestamp)

Add a filter to only return the active invitations at the given time.

Returns:

Type Description
UserInvitationQuery

The active query

filter_by_email(email)

Add a filter on the user invitation for the email address.

Parameters:

Name Type Description Default
email EmailAddress

An email address.

required

Returns:

Type Description
UserInvitationQuery

The active query

filter_by_id(id_)

Add a filter on the user invitation for id.

Parameters:

Name Type Description Default
id_(UserInvitationIdentifier)

An id of a user invitation.

required

Returns:

Type Description
UserInvitationQuery

The active query

filter_by_uuid(uuid)

Add a filter on the user invitation for the unique id.

Parameters:

Name Type Description Default
uuid(UniqueId)

A unique id of a user invitation.

required

Returns:

Type Description
UserInvitationQuery

The active query

user_invitation_repository

Module that defines an interface for an invitation repository.

UserInvitationNotFoundException

Bases: Exception

Raised when the invitation could not be found.

UserInvitationRepository

Bases: ABC

An invitation repository interface.

create(invitation) abstractmethod async

Create a new invitation.

Parameters:

Name Type Description Default
invitation(UserInvitationEntity)

The invitation to create.

required
create_query() abstractmethod

Create a UserInvitationQuery.

Returns:

Type Description
UserInvitationQuery

A query for user invitations.

delete(invitation) abstractmethod async

Delete the invitation.

Parameters:

Name Type Description Default
invitation(UserInvitationEntity)

The invitation to delete.

required
get_all(query, limit=None, offset=None) abstractmethod async

Return all user invitations from the query.

Parameters:

Name Type Description Default
query UserInvitationQuery

The prepared query.

required
limit int | None

The maximum number of entities to return.

None
offset int | None

Skip the offset rows before beginning to return entities.

None

Yields:

Type Description
AsyncIterator[UserInvitationEntity]

A list of user invitation entities.

get_invitation_by_id(id_) abstractmethod async

Get an invitation using the id.

Parameters:

Name Type Description Default
id_(UserInvitationIdentifier)

The id of the invitation to search for.

required
get_invitation_by_uuid(uuid) abstractmethod async

Get an invitation using the unique id.

Parameters:

Name Type Description Default
uuid(UniqueId)

The unique id to use for searching the invitation.

required
update(invitation) abstractmethod async

Update an existing invitation.

Parameters:

Name Type Description Default
invitation(UserInvitationEntity)

The invitation to update.

required
user_invitation_tables

Module that defines all dataclasses for the tables containing invitations.

UserInvitationRow dataclass

Represent a table row in the invitations table.

Attributes:

Name Type Description
id(int)

the id of the invitation

email(str)

the email that received this invitation

first_name(str)

the firstname of the invited

last_name(str)

the lastname of the invited

uuid(str)

a unique uuid for the invitation

expired_at(datetime)

the timestamp when the invitation expires

remark(str|None)

a remark about the invitation

user_id(int)

the user that created the invitation

confirmed_at(datetime|None)

the timestamp when the invitation was used

revoked(bool)

is the invitation revoked?

created_at(datetime)

the timestamp of creation

updated_at(datetime|None)

the timestamp of the last modification

mailed_at(datetime|None)

the timestamp of sending the email

create_entity(user)

Create a user invitation entity from the table row.

Parameters:

Name Type Description Default
user(UserEntity)

The associated user entity

required

Returns:

Type Description
UserInvitationEntity

(UserInvitationEntity)

persist(invitation) classmethod

Persist a user invitation entity into a table row.

Parameters:

Name Type Description Default
invitation(UserInvitationEntity)

The user invitation entity to persist.

required

Returns:

Type Description
UserInvitationRow

A dataclass containing the table row data.

user_invitation_tasks

Module that defines entry points for tasks for user invitations.

email_user_invitation_task(event) async

Task for sending the user invitation email.

user_recoveries

Package that defines all modules to recover a user.

user_recovery

Module that implements a user recovery entity.

UserRecoveryEntity

Bases: Entity[UserRecoveryIdentifier]

A user recovery domain.

confirmed: bool property

Return True when this user recovery was confirmed.

confirmed_at: LocalTimestamp property

Return the timestamp of the confirmation.

expiration: LocalTimestamp property

Return the expiration timestamp.

is_expired: bool property

Return True when the user recovery is expired.

mailed: bool property

Return True if the email has already been sent.

mailed_at: LocalTimestamp property

Return the timestamp of mail.

remark: str property

Return the remark.

traceable_time: TraceableTime property

Return the creation/modification timestamps.

user: UserEntity property

Return the user.

uuid: UniqueId property

Return the unique id of the user recovery.

confirm()

Confirm the user recovery.

mail_sent()

Set the timestamp when mail has been sent.

user_recovery_db_repository

Module that implements a user recovery repository interface for a database.

UserRecoveryDbRepository

Bases: UserRecoveryRepository

A user recovery repository for a database.

user_recovery_events

Module that defines all user recovery events.

UserRecoveryCreatedEvent dataclass

Bases: Event

Event that is raised when a user recovery is created.

user_recovery_mailer

Module that defines a mailer for a user recovery email.

UserRecoveryMailer

Bases: MailerService

Sends a user recovery mail.

user_recovery_repository

Module that defines an interface for a user recovery repository.

UserRecoveryNotFoundException

Bases: Exception

Raised when the user recovery could not be found.

UserRecoveryRepository

Interface for a user recovery repository.

create(user_recovery) abstractmethod async

Save a new user recovery.

delete(user_recovery) abstractmethod async

Deletes a user recovery.

get_by_uuid(uuid) abstractmethod async

Get a user recovery with the given unique id.

update(user_recovery) abstractmethod async

Save a user recovery.

user_recovery_tables

Module that defines the table for a user recovery.

UserRecoveryRow dataclass

Represent a row in the user recovery table.

create_entity(user)

Create a user recovery entity from the table row.

persist(user_recovery) classmethod

Map a user recovery entity to a table record.

user_recovery_tasks

Module that defines entry points for tasks for user recoveries.

email_user_recovery_task(event) async

Actor for sending a user recovery mail.

users

Package for all modules related to users.

user

Module that implements a User entity.

UserEntity

Bases: Entity[UserIdentifier]

A user entity.

email: EmailAddress property

Return the email address of the user.

name: Name property

Return the name of the user.

remark: str property

Return the remark for the user.

traceable_time: TraceableTime property

Return the creation/modification timestamp of the user.

uuid: UniqueId property

Return the unique id the user.

mark_for_update()

Mark the user as updated.

user_account

Module that implements a user account entity.

UserAccountEntity

Bases: Entity[UserAccountIdentifier]

A user account entity.

admin: bool property

Check if this user an administrator.

last_login: LocalTimestamp property

Return the timestamp of the last successful login.

last_unsuccessful_login: LocalTimestamp property

Return the timestamp of the last unsuccessful login.

password: Password property

Return the password of the user.

revoked: bool property

Check if this user is revoked.

user: UserEntity property

Return the associated user entity.

login(password)

Check if the given password is correct.

When login succeeds, last_login will be updated. When login fails, last_unsuccessful_login will be updated.

Parameters:

Name Type Description Default
password(str)

The password.

required
reset_password(password)

Reset the password of the user account.

Parameters:

Name Type Description Default
password(Password)

The new password.

required
revoke()

Revoke a user account.

user_account_db_repository

Module that implements a user account repository for a database.

UserAccountDbRepository

Bases: UserAccountRepository

User account repository for a database.

user_account_repository

Module that defines a repository for a user account.

UserAccountNotFoundException

Bases: Exception

Raised when a user account cannot be found.

UserAccountRepository

Interface for a user account repository.

create(user_account) abstractmethod async

Save a new user account.

delete(user_account) abstractmethod async

Delete a user account.

exists_with_email(email) async

Check if a user account with the given email address already exists.

Parameters:

Name Type Description Default
email EmailAddress

The email address to check.

required

Returns:

Type Description
bool

True when a user with the given email address exists.

get_user_by_email(email) abstractmethod async

Get a user account with the given email address.

update(user_account) abstractmethod async

Save a user account.

user_db_query

Module that implements the UserQuery interface for a database.

UserDbQuery

Bases: UserQuery, DatabaseQuery

A user query for a database.

filter_by_email(email)

Add a filter for a user with the given email address.

filter_by_id(id_)

Add a filter for a user with the given id.

filter_by_uuid(uuid)

Add a filter for a user with the given unique id.

user_db_repository

Module for implementing a user repository with a database.

UserDbRepository

Bases: UserRepository

Database repository for the user entity.

create_query()

Create a user database query.

get_user_by_email(email) async

Get the user with the given email.

UserNotFoundException is raised when the user does not exist.

get_user_by_id(id_) async

Get the user with the given id.

UserNotFoundException is raised when the user does not exist.

get_user_by_uuid(uuid) async

Get the user with the given uuid.

UserNotFoundException is raised when the user does not exist.

user_query

Module that defines the interface for a user query.

UserQuery

Bases: Query

Interface for a user query.

filter_by_email(email)

Add a filter for a user with the given email address.

filter_by_id(id_) abstractmethod

Add a filter to the query for the id of the user.

filter_by_uuid(uuid)

Add a filter for a user with the given unique id.

user_repository

Module that defines the interface for a user repository.

UserNotFoundException

Bases: Exception

Raised when a user could not be found.

UserRepository

Bases: ABC

A user repository interface.

get_user_by_email(email) abstractmethod async

Get a user using his/her email address.

get_user_by_id(id_) abstractmethod async

Get a user using the id.

get_user_by_uuid(uuid) abstractmethod async

Get a user using the unique id.

update(user) abstractmethod async

Update an existing user entity.

user_tables

Modules that defines all table classes for a user.

UserAccountRow dataclass

Represent a row in the user table with user account information.

create_entity()

Create a user account entity from the table row.

persist(user_account) classmethod

Transform a user account entity into a table record.

UserRow dataclass

Represent a row in the users table.

create_entity()

Create a user entity from a table row.

persist(user) classmethod

Transform a user entity into a table record.

news

The news module is responsible for everything that relates to news.

get_stories

Implement the use case: get news stories.

GetStories

Implementation of the use case.

Use this use case for getting news stories.

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo StoryRepository

A repository for getting the news stories.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetStoriesCommand

The input for this use case.

required

Returns:

Type Description
UseCaseBrowseResult

A tuple with the number of entities and an iterator for story entities.

GetStoriesCommand dataclass

Input for use case: GetStories.

Attributes:

Name Type Description
offset int | None

Offset to use. Default is None.

limit int | None

The max. number of elements to return. Default is None, which means all.

enabled bool

When False, also stories that are not activated will be returned.

stories

Package for all modules related to stories.

story

Module that defines a story entity.

Application dataclass

Value object for an application.

Author dataclass

Value object for an author of content.

Promotion dataclass

Value object for handling promoted news stories.

StoryEntity

Bases: Entity[StoryIdentifier]

A story entity.

application: Application property

Return the application.

content: list[LocaleText] property

Return the contents of the story.

Remark

The list is a copy

is_enabled: bool property

Check if the story is enabled.

period: Period property

Return the active period of the story.

promotion: Promotion property

Return the promotion information of the story.

remark: str property

Return the remark.

traceable_time: TraceableTime property

Return the creation/modification timestamp of this application.

story_db_query

Module that implements a StoryQuery for a database.

StoryDbQuery

Bases: StoryQuery, DatabaseQuery

A database query for news stories.

story_db_repository

Module that implements a story repository for a database.

StoryDbRepository

Bases: StoryRepository

A story database repository.

Attributes:

Name Type Description
_database

the database for the repository.

story_query

Module for defining a interface for a story query.

StoryQuery

Bases: Query

An interface for a story query.

filter_by_active() abstractmethod

Add a filter to only return active news stories.

An active story is enabled and is not expired.

filter_by_application(application) abstractmethod

Add a filter to return only stories for the given application.

Parameters:

Name Type Description Default
application int | str

The id or the name of the application

required
filter_by_id(id_) abstractmethod

Add a filter on the news story id.

Parameters:

Name Type Description Default
id_ StoryIdentifier

an id of a news story.

required
filter_by_promoted() abstractmethod

Add a filter to return only the promoted news stories.

filter_by_publication_date(year, month=None) abstractmethod

Add a filter on the publication date.

Parameters:

Name Type Description Default
year int

Only return news stories published in this year.

required
month int | None

Only return news stories published in this month.

None

When month is omitted, all stories published in the given year will be returned.

filter_by_user(user) abstractmethod

Add a filter to only return news stories of the given user.

Parameters:

Name Type Description Default
user int | UniqueId

The id or unique id of the user.

required
order_by_publication_date() abstractmethod

Order the result on the publication date.

story_repository

Module that defines an interface for a story repository.

StoryNotFoundException

Bases: Exception

Raised when the story can not be found.

StoryRepository

Bases: ABC

Interface for a story repository.

create(story) abstractmethod async

Create a new story entity.

Parameters:

Name Type Description Default
story StoryEntity

The story to create

required

Returns:

Type Description
StoryEntity

The story entity with an identifier.

create_query() abstractmethod

Create a query for querying stories.

delete(story) abstractmethod async

Delete a story.

Parameters:

Name Type Description Default
story StoryEntity

The story to delete.

required
get_all(query=None, limit=None, offset=None) abstractmethod async

Return all stories of a given query.

Parameters:

Name Type Description Default
query StoryQuery | None

The query to use for selecting the rows.

None
limit int | None

The maximum number of entities to return.

None
offset int | None

Skip the offset rows before beginning to return entities.

None

Yields:

Type Description
AsyncIterator[StoryEntity]

A list of stories.

get_by_id(id_) abstractmethod async

Get the story with the given id.

Parameters:

Name Type Description Default
id_ StoryIdentifier

The id of the story.

required

Returns:

Type Description
StoryEntity

A story entity.

update(story) abstractmethod async

Update a story entity.

Parameters:

Name Type Description Default
story StoryEntity

The story to update.

required
story_tables

Module that defines all dataclasses for the tables containing stories.

ApplicationRow dataclass

Represent the application data that is associated with a story.

create_application()

Create an Application value object from row data.

StoryContentRow dataclass

Bases: ContentRow

Represent a row in the news_contents table.

Attributes:

Name Type Description
news_id int

The id of the news story

persist(story, content) classmethod

Persist a content value object to the table.

Parameters:

Name Type Description Default
story StoryEntity

The story that contains the content.

required
content LocaleText

The content of a story.

required
StoryRow dataclass

Represent a table row of the stories table.

Attributes:

Name Type Description
id int

the id of the story

enabled int

is the story enabled?

promotion int

the priority to use for the promotion

promotion_end_date datetime | None

when ends the promotion?

publish_date datetime

time of publication

end_date datetime | None

end of publication

remark str | None

a remark about the story

application_id int

the link to the application

created_at datetime

the timestamp of creation

updated_at datetime | None

the timestamp of the last modification

create_entity(application, content)

Create a story entity from a table row.

persist(story) classmethod

Persist an entity to row data.

Parameters:

Name Type Description Default
story StoryEntity

The story to persist.

required

portal

The portal module is responsible for everything that relates to a portal.

kwai.modules.portal.get_applications

Module that defines the use case: get all applications for a portal.

GetApplications

Implements the use case 'get applications'.

__init__(application_repo)

Initialize the use case.

Parameters:

Name Type Description Default
application_repo ApplicationRepository

A repository for getting applications.

required

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetApplicationsCommand

The input for this use case.

required

GetApplicationsCommand dataclass

Input for the use case GetApplications.

Attributes:

Name Type Description
name str

Only return the application with the given name

news bool

Only return applications that can contain news

events bool

Only return applications that can contain events

pages bool

Only return applications that can contain pages

applications

Package for all modules related to applications.

application

Module that defines an application entity.

ApplicationEntity

Bases: Entity[ApplicationIdentifier]

An application entity.

can_contain_events: bool property

Return True when the application can contain events.

can_contain_news: bool property

Return True when the application can contain news.

can_contain_pages: bool property

Return True when the application can contain pages.

description: str property

Return the description.

id: ApplicationIdentifier property

Return the id.

name: str property

Return the name.

remark: str property

Return the remark.

short_description: str property

Return the short description.

title: str property

Return the title.

traceable_time: TraceableTime property

Return the creation/modification timestamp of this application.

weight: int property

Return the weight.

__init__(*, id_=None, title, name, short_description, description='', remark='', news=True, pages=True, events=True, weight=0, traceable_time=None)

Initialize the application.

Parameters:

Name Type Description Default
id_ ApplicationIdentifier | None

The id of the application entity

None
title str

The title of the application

required
name str

A unique name for the application

required
short_description str

A short description for the application

required
description str

A long description for the application

''
remark str

A remark for the application

''
news bool

Can this application contain news?

True
pages bool

Can this application contain pages?

True
events bool

Can this application contain events?

True
weight int

A weight, can be used to order applications.

0
traceable_time TraceableTime | None

The creation and modification timestamp of the application.

None
application_db_query

Module that implements an ApplicationQuery for a database.

ApplicationDbQuery

Bases: ApplicationQuery, DatabaseQuery

A database query for an application.

application_db_repository

Module that implements an application repository for a database.

ApplicationDbRepository

Bases: ApplicationRepository

An application database repository.

Attributes:

Name Type Description
_database

the database for this repository.

application_query

Module that defines an interface for an application query.

ApplicationQuery

Bases: Query, ABC

An interface for querying applications.

filter_by_id(id_) abstractmethod

Add a filter on the application id.

Parameters:

Name Type Description Default
id_ ApplicationIdentifier

an id of an application.

required
filter_by_name(name) abstractmethod

Add a filter on the application name.

Parameters:

Name Type Description Default
name str

the name of an application.

required
filter_only_events() abstractmethod

Only return applications which can contain events.

filter_only_news() abstractmethod

Only return applications which can contain news.

filter_only_pages() abstractmethod

Only return applications which can contain pages.

application_repository

Module that defines an interface for an application repository.

ApplicationNotFoundException

Bases: Exception

Raised when the application can not be found.

ApplicationRepository

Bases: ABC

An application repository interface.

create(application) abstractmethod async

Create a new application entity.

Parameters:

Name Type Description Default
application ApplicationEntity

The application to create.

required
create_query() abstractmethod

Create a query for querying applications.

delete(application) abstractmethod async

Delete an application entity.

Parameters:

Name Type Description Default
application ApplicationEntity

The application to delete.

required
get_all(query=None, limit=None, offset=None) abstractmethod async

Return all applications of a given query.

Parameters:

Name Type Description Default
query ApplicationQuery | None

The query to use for selecting the rows.

None
limit int | None

The maximum number of entities to return.

None
offset int | None

Skip the offset rows before beginning to return entities.

None

Yields:

Type Description
AsyncIterator[ApplicationEntity]

A list of applications.

get_by_id(id_) abstractmethod async

Get the application with the given id.

Parameters:

Name Type Description Default
id_ ApplicationIdentifier

The id of the application.

required

Returns:

Type Description
ApplicationEntity

An application entity.

Raises:

Type Description
ApplicationNotFoundException

when the application does not exist.

get_by_name(name) abstractmethod async

Get the application with the given name.

Parameters:

Name Type Description Default
name str

The name of the application.

required

Returns:

Type Description
ApplicationEntity

An application entity.

Raises:

Type Description
ApplicationNotFoundException

when the application with the given name does not exist.

update(application) abstractmethod async

Update an application entity.

Parameters:

Name Type Description Default
application ApplicationEntity

The application to update.

required
application_tables

Module that defines all dataclasses for the tables containing applications.

ApplicationRow dataclass

Represent a table row of the applications table.

Attributes:

Name Type Description
id int

the id of the application

title str

the title of the application

name str

a unique name for the application

short_description str

a short description about the application

description str | None

a description about the application

remark str | None

a remark about the application

news int

does this application can contain news stories?

pages int

does this application can contain pages?

weight int

a weight that can be used to order the applications

created_at datetime

the timestamp of creation

updated_at datetime | None

the timestamp of the last modification

create_entity()

Create an application entity from a table row.

Returns:

Type Description
ApplicationEntity

An application entity.

persist(application) classmethod

Persist an application entity.

Parameters:

Name Type Description Default
application ApplicationEntity

the entity to persist.

required

Returns:

Type Description
ApplicationRow

A dataclass containing the table row data.

get_applications

Module that defines the use case: get all applications for a portal.

GetApplications

Implements the use case 'get applications'.

__init__(application_repo)

Initialize the use case.

Parameters:

Name Type Description Default
application_repo ApplicationRepository

A repository for getting applications.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetApplicationsCommand

The input for this use case.

required
GetApplicationsCommand dataclass

Input for the use case GetApplications.

Attributes:

Name Type Description
name str

Only return the application with the given name

news bool

Only return applications that can contain news

events bool

Only return applications that can contain events

pages bool

Only return applications that can contain pages

training

Package for the training module.

This module implements a bounded context for trainings. It is responsible for managing trainings and training definitions.

Entities
TrainingEntity

A TrainingEntity represents one training of one or more teams. One or more coaches can be assigned to a training.

Class documentation: TrainingEntity.

TrainingDefinitionEntity

A TrainingDefinitionEntity contains information to create recurring trainings.

Class documentation: TrainingDefinitionEntity

coaches

Package for all modules related to coaches of a training.

coach

Module that defines a coach entity.

CoachEntity

Bases: Entity[CoachIdentifier]

A coach.

Attributes:

Name Type Description
_id

The id of the coach.

_name

The name of the coach.

is_active: bool property

Return True when the coach is still active, False otherwise.

name: Name property

Return the name of the coach.

coach_db_repository

Module that defines a coach repository for a database.

CoachDbRepository

Bases: CoachRepository

A coach repository for a database.

__init__(database)

Initialize the repository.

Parameters:

Name Type Description Default
database Database

The database for this repository.

required
coach_repository

Module that defines an interface for a coach repository.

CoachNotFoundException

Bases: Exception

Raised when a coach is not found.

CoachRepository

Bases: ABC

Interface for a coach repository.

get_by_id(id) abstractmethod async

Get the coach with the given id.

Parameters:

Name Type Description Default
id CoachIdentifier

The id of a coach.

required

Raises:

Type Description
CoachNotFoundException

raised when the coach with the given id does not exist.

get_by_ids(*id) abstractmethod async

Get all coaches for the given ids.

Parameters:

Name Type Description Default
id CoachIdentifier

A variable number of coach ids.

()
coach_tables

Module that defines all dataclasses for the tables containing coaches.

CoachRow dataclass

Represent a row of the coaches table.

create_entity(person_row)

Create a coach entity from this row.

PersonRow dataclass

Represent a row of the persons table.

create_training

Module for the use case "Create training".

CreateTraining

Use case for creating a training.

__init__(repo, definition_repo, coach_repo, team_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingRepository

The repository used to create the training.

required
definition_repo TrainingDefinitionRepository

The repository for getting the training definition.

required
coach_repo CoachRepository

The repository for getting the coaches.

required
team_repo TeamRepository

The repository for getting the teams.

required
owner Owner

The user that executes this use case.

required
execute(command) async

Executes the use case.

Parameters:

Name Type Description Default
command CreateTrainingCommand

The input for this use case.

required

Raises:

Type Description
TrainingDefinitionNotFoundException

Raised when a training definition cannot be found.

delete_training

Module that defines the use case "Delete Training".

DeleteTraining

Use case for deleting a training.

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingRepository

A repository for deleting the training.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command DeleteTrainingCommand

The input for the use case.

required

Raises:

Type Description
TrainingNotFoundException

raised when the training does not exist.

DeleteTrainingCommand dataclass

Input for the use case DeleteTraining.

get_training

Module for the use case get training.

GetTraining

Use case to get a training.

__init__(repo)

Initialize the use case.

Attributes:

Name Type Description
repo

The repository for trainings.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetTrainingCommand

the input for this use case.

required

Raises:

Type Description
TrainingNotFoundException

Raised when the training with the given id does not exist.

Returns:

Type Description
TrainingEntity

A training entity.

GetTrainingCommand dataclass

Input for the get training use case.

Attributes:

Name Type Description
id int

the id of the training.

get_trainings

Module for the use case get trainings.

GetTrainings

Use case to get trainings.

__init__(repo, coach_repo, training_definition_repo)

Initialize use case.

Attributes:

Name Type Description
repo

The repository for trainings.

coach_repo

The repository for coaches.

training_definition_repo

The repository for training definitions.

execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetTrainingsCommand

The input for this use case.

required

Raises:

Type Description
CoachNotFoundException

Raised when a coach is not found.

TrainingDefinitionNotFoundException

Raised when a definition is not found.

Returns:

Type Description
UseCaseBrowseResult

A tuple with the number of entities and an iterator for training entities.

GetTrainingsCommand dataclass

Input for the get trainings use case.

Attributes:

Name Type Description
limit int | None

the max. number of elements to return. Default is None, which means all.

offset int | None

Offset to use. Default is None.

year int | None

Only return trainings of this year.

month int | None

Only return trainings of this month.

start datetime | None

Only return trainings starting from this date.

end datetime | None

Only return trainings before this date.

coach int | None

Only return trainings with this coach.

definition int | None

Only return trainings created from this definition.

active bool

Only return trainings that are active (default is True).

teams

Package for all modules related to teams of a training.

team

Module that defines a team entity.

TeamEntity

Bases: Entity[TeamIdentifier]

A team.

Attributes:

Name Type Description
_id

The id of the team.

_name

The name of the team.

name: str property

Return the name of the team.

team_db_repository

Module that defines a team repository for a database.

TeamDbRepository

Bases: TeamRepository

A team repository for a database.

__init__(database)

Initialize the repository.

Parameters:

Name Type Description Default
database Database

The database for this repository.

required
team_repository

Module that defines an interface for a team repository.

TeamRepository

Bases: ABC

Interface for a team repository.

get_by_ids(*ids) abstractmethod async

Get all teams for the given ids.

Parameters:

Name Type Description Default
ids TeamIdentifier

A variable number of team ids.

()
team_tables

Module that defines all dataclasses for the team tables.

TeamRow dataclass

Represent a row of the teams table.

create_entity()

Create a Team entity of this row.

training_command

Module that defines common input for the use cases of Trainings.

Coach dataclass

Input for a coach associated with a training.

TrainingCommand dataclass

Input for the create or update Training use case.

trainings

Package for all modules related to trainings.

training

Module for defining a training entity.

TrainingEntity

Bases: Entity[TrainingIdentifier]

A training entity.

active: bool property

Return if the training is active or not.

cancelled: bool property

Return if the training is cancelled or not.

coaches: list[TrainingCoach] property

Return the coaches attached to the training.

Remark

The list is a copy

content: list[LocaleText] property

Return the text content of a training.

Remark

The list is a copy.

definition: TrainingDefinitionEntity | None property

Return the related training definition.

id: TrainingIdentifier property

Return the id of the training.

location: str property

Return the location of the training.

period: Period property

Return the period of the training.

remark: str | None property

Return the remark.

teams: list[TeamEntity] property

Return the teams of the training.

Remark

The list is a copy

traceable_time: TraceableTime property

Return the traceable time of the training.

__init__(*, id_=None, content, definition=None, coaches=None, teams=None, season=None, period, active=True, cancelled=False, location='', remark='', traceable_time=None)

Initialize a training.

Parameters:

Name Type Description Default
id_ TrainingIdentifier | None

The id of the training

None
content list[LocaleText]

A list with text content

required
definition TrainingDefinitionEntity | None

The related definition, when the training was created from a definition.

None
coaches list[TrainingCoach] | None

A list of assigned coaches.

None
teams list[TeamEntity] | None

A list of assigned teams.

None
period Period

The period of the training.

required
season None

The season that the training belongs to (not supported yet).

None
active bool

Is this training active?

True
cancelled bool

Is this training cancelled?

False
location str

The location of this training

''
remark str

A remark about this training

''
traceable_time TraceableTime | None

The creation and modification timestamp of the training.

None
training_coach_db_query

Module that defines a database query to get coaches of training(s).

TrainingCoachDbQuery

Bases: DatabaseQuery

A database query for getting coaches of training(s).

fetch_coaches() async

Fetch coaches.

A specialized fetch method that already transforms the records into TrainingCoach objects.

Returns:

Type Description
dict[TrainingIdentifier, list[TrainingCoach]]

A dictionary that contains the list of coaches for trainings. The key

dict[TrainingIdentifier, list[TrainingCoach]]

is the identifier of a training.

filter_by_trainings(*ids)

Filter by trainings.

Only the rows of the trainings with the given ids, will be returned.

training_db_query

Module that implements a training query for a database.

TrainingDbQuery

Bases: TrainingQuery, DatabaseQuery

A database query for trainings.

training_db_repository

Module for implementing a training repository for a database.

TrainingDbRepository

Bases: TrainingRepository

A training repository for a database.

__init__(database)

Initialize the repository.

Parameters:

Name Type Description Default
database Database

The database for this repository.

required
training_definition

Module for defining a training definition entity.

TrainingDefinitionEntity

Bases: Entity[TrainingDefinitionIdentifier]

A training definition entity.

A training definition can be used to create recurring trainings.

active: bool property

Return True when the training definition is active.

description: str property

Return the description of the training definition.

id: TrainingDefinitionIdentifier property

Return the id of the training definition.

location: str property

Return the location of the training definition.

name: str property

Return the name of the training definition.

owner: Owner property

Return the owner of the training definition.

period: TimePeriod property

Return the period of the training definition.

remark: str property

Return the remark of the training definition.

traceable_time: TraceableTime property

Return the creation/modification timestamp of this training definition.

weekday: Weekday property

Return the weekday of the training definition.

__init__(*, id_=None, name, description, weekday, period, active=True, location='', remark='', owner, traceable_time=None)

Initialize a training definition.

Parameters:

Name Type Description Default
id_ TrainingDefinitionIdentifier | None

The id of the training definition.

None
name str

The name of the training definition.

required
description str

A description of the training definition.

required
weekday Weekday

The weekday to use to create the recurring trainings.

required
period TimePeriod

The time period to use to create the recurring trainings.

required
active bool

Is this definition active?

True
location str

The location of the recurring trainings.

''
remark str

A remark about this training definition.

''
owner Owner

The owner of this training definition.

required
traceable_time TraceableTime | None

The creation and modification timestamp of the definition.

None
training_definition_db_query

Module that implements a TrainingDefinitionQuery for a database.

TrainingDefinitionDbQuery

Bases: DatabaseQuery, TrainingDefinitionQuery

A database query for a training definition.

training_definition_db_repository

Module that implements a training definition repository for a database.

TrainingDefinitionDbRepository

Bases: TrainingDefinitionRepository

A training definition repository for a database.

__init__(database)

Initialize the repository.

Parameters:

Name Type Description Default
database Database

The database for this repository

required
training_definition_query

Module that defines an interface for a training definition query.

TrainingDefinitionQuery

Bases: Query, ABC

Interface for a training definition query.

filter_by_id(id_) abstractmethod

Add a filter on the training definition id.

Parameters:

Name Type Description Default
id_ TrainingDefinitionIdentifier

id of a training definition

required

Returns:

Name Type Description
TrainingDefinitionQuery TrainingDefinitionQuery
filter_by_ids(*ids) abstractmethod

Add a filter on multiple training definition identifiers.

Parameters:

Name Type Description Default
ids TrainingDefinitionIdentifier

a variable list of training definition identifiers

()

Returns:

Name Type Description
TrainingDefinitionQuery TrainingDefinitionQuery
training_definition_repository

Module that defines an interface for a training definition repository.

TrainingDefinitionNotFoundException

Bases: Exception

Raised when a training definition can not be found.

TrainingDefinitionRepository

Bases: ABC

A training definition repository.

create(training_definition) abstractmethod async

Create a new training definition entity.

Parameters:

Name Type Description Default
training_definition TrainingDefinitionEntity

The training definition to create.

required
create_query() abstractmethod

Create a query for querying training definitions.

delete(training_definition) abstractmethod async

Delete an application entity.

Parameters:

Name Type Description Default
training_definition TrainingDefinitionEntity

The training definition to delete.

required
get_all(query=None, limit=None, offset=None) abstractmethod async

Return all training definitions of a given query.

Parameters:

Name Type Description Default
query TrainingDefinitionQuery | None

The query to use for selecting the rows.

None
limit int | None

The maximum number of entities to return.

None
offset int | None

Skip the offset rows before beginning to return entities.

None

Yields:

Type Description
AsyncIterator[TrainingDefinitionEntity]

A list of applications.

get_by_id(id_) abstractmethod async

Get the training definition with the given id.

Parameters:

Name Type Description Default
id_ TrainingDefinitionIdentifier

The id of the training definition.

required

Returns:

Type Description
TrainingDefinitionEntity

A training definition

Raises:

Type Description
TrainingDefinitionNotFoundException

when the training definition cannot be found.

update(training_definition) abstractmethod async

Update an application entity.

Parameters:

Name Type Description Default
training_definition TrainingDefinitionEntity

The training definition to update.

required
training_query

Module that defines an interface for a training query.

TrainingQuery

Bases: Query, ABC

Interface for a training query.

filter_active() abstractmethod

Add filter to get only the active trainings.

filter_by_coach(coach) abstractmethod

Add filter to get only trainings for the given week.

Parameters:

Name Type Description Default
coach CoachEntity

The coach to use for the filter.

required
filter_by_dates(start, end) abstractmethod

Add filter to get only trainings between two dates.

Parameters:

Name Type Description Default
start datetime

The start date to use for the filter.

required
end datetime

The end date to use for the filter.

required
filter_by_definition(definition) abstractmethod

Add filter to get only trainings for the given definition.

Parameters:

Name Type Description Default
definition TrainingDefinitionEntity

The definition to use for the filter.

required
filter_by_id(id_) abstractmethod

Add a filter on a training identifier.

Parameters:

Name Type Description Default
id_ TrainingIdentifier

id of a training.

required
filter_by_team(team) abstractmethod

Add filter to get only trainings for the given team.

Parameters:

Name Type Description Default
team TeamEntity

The team to use for the filter.

required
filter_by_year_month(year, month=None) abstractmethod

Add filter to get only trainings for the given year/month.

Parameters:

Name Type Description Default
year int

The year to use for the filter.

required
month int | None

The month to use for the filter.

None
order_by_date() abstractmethod

Order the trainings by date.

training_repository

Module that defines an interface for a repository of trainings.

TrainingNotFoundException

Bases: Exception

Raised when a training can not be found.

TrainingRepository

Bases: ABC

An interface for a repository of trainings.

create(training) abstractmethod async

Save a training.

Parameters:

Name Type Description Default
training TrainingEntity

The training to save.

required

Returns:

Type Description
TrainingEntity

A training entity with an identifier.

create_query() abstractmethod

Create a query for querying trainings.

delete(training) abstractmethod async

Delete a training.

Parameters:

Name Type Description Default
training TrainingEntity

The training to delete.

required
get_all(query=None, limit=None, offset=None) abstractmethod async

Return all trainings of a given query.

Parameters:

Name Type Description Default
query TrainingQuery | None

The query to use for selecting the rows.

None
limit int | None

The maximum number of entities to return.

None
offset int | None

Skip the offset rows before beginning to return entities.

None

Returns:

Type Description
AsyncIterator[TrainingEntity]

A list of trainings.

get_by_id(id) abstractmethod async

Get the training with the given id.

Parameters:

Name Type Description Default
id TrainingIdentifier

The id of the training.

required

Returns:

Type Description
TrainingEntity

A training entity.

update(training) abstractmethod async

Update a training.

Parameters:

Name Type Description Default
training TrainingEntity

The training to save.

required
training_tables

Module that defines all dataclasses for the tables containing trainings.

TrainingCoachRow dataclass

Represent a row of the training_coaches table.

create_coach(coach, owner)

Create a TrainingCoach value object.

persist(training, training_coach) classmethod

Persist a TrainingCoach value object into a table row.

TrainingContentRow dataclass

Bases: ContentRow

Represent a row in the training_contents table.

Attributes:

Name Type Description
training_id int

The id of the training

persist(training, content) classmethod

Persist a content value object to this table.

Parameters:

Name Type Description Default
training TrainingEntity

The training that contains the text content.

required
content LocaleText

The text content of the training.

required
TrainingDefinitionRow dataclass

Represent a table row of the training definitions table.

create_entity(owner)

Create a training definition entity from a table row.

Parameters:

Name Type Description Default
owner Owner

The owner of the training definition.

required

Returns:

Type Description
TrainingDefinitionEntity

A training definition entity.

persist(training_definition) classmethod

Persist a training definition entity.

TrainingRow dataclass

Represent a table row of the trainings table.

Attributes:

Name Type Description
id int

the id of the training

definition_id int | None

the id of the relation training definition

season_id int | None

the id of the related season

created_at datetime

the timestamp of creation

updated_at datetime | None

the timestamp of the last modification

start_date datetime

the timestamp of the start of the training

end_date datetime

the timestamp of the end of the training

active int

is this training active?

cancelled int

is this training cancelled?

location str | None

the location of the training

remark str | None

a remark about the training

create_entity(content, definition=None)

Create a training entity from the table row.

Returns:

Type Description
TrainingEntity

A training entity.

persist(training) classmethod

Persist a training.

Parameters:

Name Type Description Default
training TrainingEntity

The training to persist.

required

Returns:

Type Description
TrainingRow

A dataclass containing the table row data.

TrainingTeamRow dataclass

Represent a row of the training_teams table.

persist(training, team) classmethod

Persist a team of a training to a table row.

training_team_db_query

Module that defines a database query to get teams of training(s).

TrainingTeamDbQuery

Bases: DatabaseQuery

A database query for getting teams of training(s).

fetch_teams() async

Fetch teams.

A specialized fetch method that already transforms the records into Team objects.

Returns:

Type Description
dict[TrainingIdentifier, list[TeamEntity]]

A dictionary that contains the list of teams for trainings. The key

dict[TrainingIdentifier, list[TeamEntity]]

is the identifier of a training.

filter_by_trainings(*ids)

Filter by trainings.

Only the rows of the trainings with the given ids, will be returned.

value_objects

Module that defines a value objects for the bounded context trainings.

Season dataclass

A season.

Attributes:

Name Type Description
id IntIdentifier

The id of the season.

name str

The name of the season.

TrainingCoach dataclass

A coach attached to a training.

update_training

Module for defining the use case "Update Training".

UpdateTraining

Use case for updating a training.

__init__(repo, definition_repo, coach_repo, team_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingRepository

The repository used to create the training.

required
definition_repo TrainingDefinitionRepository

The repository for getting the training definition.

required
coach_repo CoachRepository

The repository for getting the coaches.

required
team_repo TeamRepository

The repository for getting the teams.

required
owner Owner

The user that executes this use case.

required
execute(command) async

Executes the use case.

Parameters:

Name Type Description Default
command UpdateTrainingCommand

The input for this use case.

required

Raises:

Type Description
TrainingDefinitionNotFoundException

Raised when a training definition cannot be found.

UpdateTrainingCommand dataclass

Bases: TrainingCommand

Input for the "Update Training" use case.