Skip to content

Reference

kwai

kwai is the main package of the backend.

__main__

Module for starting kwai.

When this module is used, it will start the api and frontend application. If only the api is required, use kwai.api.

api

Main package for the API.

__main__

Module for starting the api server.

This will only start the api server. Use this when the frontend is not served by FastAPI or if the api server is running on another server.

app

Module that implements a factory method for a FastAPI application.

configure_logger(settings)

Configure the logger.

create_api(settings=None)

Create the FastAPI application.

Parameters:

Name Type Description Default
settings Settings | None

Settings to use in this application.

None
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.

create_database(settings=Depends(get_settings)) async

Create the database dependency.

create_templates(settings=Depends(get_settings)) async

Create the template engine dependency.

get_current_user(settings, db, access_token=None) 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.

get_optional_user(settings, db, access_token=None) async

Try to get the current user from an access token.

When no token is available in the request, None will be returned.

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

get_publisher(settings=Depends(get_settings)) async

Get the publisher dependency.

schemas

Package that contains all schemas used in the API.

application

Schemas for an application resource.

ApplicationAttributes

Bases: ApplicationBaseAttributes

Attributes for an application JSON:API resource.

ApplicationBaseAttributes

Bases: BaseModel

Common attributes of an application JSON:API resource.

ApplicationDocument

Bases: Document[ApplicationResource, NoneType]

A JSON:API document for one or more applications.

create(application) classmethod

Create a document from an application entity.

ApplicationResource

Bases: ApplicationResourceIdentifier, ResourceData[ApplicationAttributes, NoneType]

A JSON:API resource for an application.

news_item

Schemas for a news item.

NewsItemApplicationResource

Bases: ApplicationResourceIdentifier, ResourceData[ApplicationBaseAttributes, NoneType]

A JSON:API resource for an application associated with a page.

NewsItemAttributes

Bases: BaseModel

Attributes of a news item JSON:API resource.

NewsItemDocument

Bases: Document[NewsItemResource, NewsItemApplicationResource]

A JSON:API document for one or more news items.

create(news_item) classmethod

Create a document from a news item entity.

NewsItemRelationships

Bases: BaseModel

Relationships of a news item JSON:API resource.

NewsItemResource

Bases: NewsItemResourceIdentifier, ResourceData[NewsItemAttributes, NewsItemRelationships]

A JSON:API resource for a news item.

NewsItemText

Bases: BaseModel

Schema for the text of a news item.

page

Module for defining the page JSON:API resource.

PageApplicationResource

Bases: ApplicationResourceIdentifier, ResourceData[ApplicationBaseAttributes, NoneType]

A JSON:API resource for an application associated with a page.

PageAttributes

Bases: BaseModel

Attributes of a page JSON:API resource.

PageDocument

Bases: Document[PageResource, PageApplicationResource]

A JSON:API document for one or more pages.

create(page) classmethod

Create a document from a page entity.

PageRelationships

Bases: BaseModel

Relationships of a page JSON:API resource.

PageResource

Bases: PageResourceIdentifier, ResourceData[PageAttributes, PageRelationships]

A JSON:API resource for a page.

PageText

Bases: BaseModel

Schema for the text of a page.

resources

Module that defines all JSON:API resource identifiers.

ApplicationResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for an application.

CoachResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a coach.

NewsItemResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a news item.

PageResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a page.

TeamResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a team.

TrainingDefinitionResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a training definition.

TrainingResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a training.

UserInvitationResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a user invitation.

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.

/login post

Login a user.

This request expects a form (application/x-www-form-urlencoded). The form must contain a username and password field. The username is the email address of the user.

On success, a cookie for the access token and the refresh token will be returned.

This api can return the following HTTP codes:

Status Description
200 The user is logged in successfully.
401 The email is invalid, authentication failed or user is unknown.
/logout post

Log out the current user.

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

This request expects a form (application/x-www-form-urlencoded). The form must contain a refresh_token field.

This api can return the following HTTP codes:

Status Description
200 The user is logged out successfully.
404 The token is not found.
/recover post

Start a recover password flow for the given email address.

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

This request expects a form (application/x-www-form-urlencoded). The form must contain an email field.

Note

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

This api can return the following HTTP codes:

Status Description
200 Ok.
/access_token post

Refresh the access token.

On success, a new access token / refresh token cookie will be sent.

When the refresh token is expired, the user needs to log in again.

This api can return the following HTTP codes:

Status Description
200 The access token is renewed.
401 The refresh token is expired.
/reset post

Reset the password of the user.

Http code 200 on success, 404 when the unique id is invalid, 422 when the request can't be processed, 403 when the request is forbidden.

This request expects a form (application/x-www-form-urlencoded). The form must contain an uuid and password field. The unique id must be valid and is retrieved by /api/v1/auth/recover.

This api can return the following HTTP codes:

Status Description
200 The password is reset successfully.
403 This request is forbidden.
404 The uniqued id of the recovery could not be found.
422 The user could not be found.
user

Module that implements all user endpoints.

/user get

Get the current user.

This api can return the following HTTP codes:

Status Description
200 Ok.
401 Not authorized
user_invitations

Module that implements invitations endpoints.

/invitations post

Create a user invitation.

A wrong email address or a still pending user invitation will result in a 422 status code.

This api can return the following HTTP codes:

Status Description
201 User invitation is created
401 Not authorized.
422 User invitation could not be created
/invitations/{uuid} delete

Delete the user invitation with the given unique id.

This api can return the following HTTP codes:

Status Description
200 User invitation is deleted.
401 Not authorized.
404 User invitation does not exist.
422 Invalid unique id passed for the user invitation.
/invitations/{uuid} get

Get the user invitation with the given unique id.

This api can return the following HTTP codes:

Status Description
200 Ok.
401 Not authorized.
/invitations get

Get all user invitations.

Use the page[offset] and page[limit] query parameters to get a paginated result.

This api can return the following HTTP codes:

Status Description
200 Ok.
401 Not authorized.
schemas

Package for schemas of the auth API.

user_invitation

Schemas for a user invitation resource.

UserInvitationAttributes

Bases: BaseModel

Attributes of a user invitation JSON:API resource.

UserInvitationDocument

Bases: Document[UserInvitationResource, None]

A JSON:API document for one or more user invitations.

create(user_invitation) classmethod

Create a document for a user invitation.

UserInvitationResource

Bases: UserInvitationResourceIdentifier, ResourceData[UserInvitationAttributes, None]

A JSON:API resource of a user invitation.

club

Package for the members API.

api

Module that defines the members API.

endpoints

Package that contains endpoints for the members API.

members

Module for defining the endpoints for members of the club API.

MembersFilterModel

Bases: BaseModel

Define the JSON:API filter for members.

/members/{uuid} get

Get a member with the given unique id.

/members get

Get members.

upload_members

Module that defines the members API.

UploadMemberModel

Bases: BaseModel

Model containing information about a row.

The id will be set, when a member is successfully imported. When a member was not imported, the message will contain a description about the problem.

UploadMembersModel

Bases: BaseModel

Model that contains the information about all rows.

/members/upload post

Upload a members csv file.

upload_file(uploaded_file, path) async

Creates a unique file for the uploaded file.

presenters

Module that defines presenters for the club api.

JsonApiMemberPresenter

Bases: JsonApiPresenter[MemberDocument], Presenter[MemberEntity]

A presenter that transform a member entity into a JSON:API document.

JsonApiMembersPresenter

Bases: JsonApiPresenter[MemberDocument], AsyncPresenter[IterableResult[MemberEntity]]

A presenter that transform an iterator for members into a JSON:API document.

JsonApiUploadMemberPresenter

Bases: JsonApiPresenter[MemberDocument], Presenter[MemberImportResult]

A presenter that transform a file upload of a member into a JSON:API document.

schemas

Package for defining schemas for the club API.

contact

Module for defining the JSON:API resource for a contact.

ContactAttributes

Bases: BaseModel

Attributes for the contact JSON:API resource.

ContactDocument

Bases: Document[ContactResource, ContactInclude]

A JSON:API document for one or more contact resources.

create(contact) classmethod

Create a contact document from a contact entity.

ContactRelationships

Bases: BaseModel

Relationships for the contact JSON:API resource.

ContactResource

Bases: ContactResourceIdentifier, ResourceData[ContactAttributes, ContactRelationships]

A JSON:API resource for a contact.

member

Module for defining the JSON:API resource for a member.

MemberAttributes

Bases: BaseModel

Attributes for the member JSON:API resource.

MemberDocument

Bases: Document[MemberResource, MemberInclude]

A JSON:API document for one or more member resources.

create(member) classmethod

Create a member document from a member entity.

MemberRelationships

Bases: BaseModel

Relationships of a member JSON:API resource.

MemberResource

Bases: MemberResourceIdentifier, ResourceData[MemberAttributes, MemberRelationships]

A JSON:API resource for a member.

person

Module for defining the JSON:API resource for a person.

PersonAttributes

Bases: BaseModel

Attributes for the person JSON:API resource.

PersonDocument

Bases: Document[PersonResource, PersonInclude]

A JSON:API document for one ore more persons.

create(person) classmethod

Create a person document from a person entity.

PersonRelationships

Bases: BaseModel

Relationships of a person JSON:API resource.

PersonResource

Bases: PersonResourceIdentifier, ResourceData[PersonAttributes, PersonRelationships]

A JSON:API resource for a person.

resources

Module that defines all JSON:API resource identifiers for the club API.

ContactResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a contact.

MemberResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a member.

PersonResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a person.

UploadResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a upload.

upload

Module for defining the JSON:API resource for an upload.

UploadAttributes

Bases: BaseModel

Attributes for the upload JSON:API resource.

UploadDocument

Bases: Document[UploadResource, NoneType]

A JSON:API document for an upload.

create(upload) classmethod

Create a document for an upload.

UploadResource

Bases: UploadResourceIdentifier, ResourceData[UploadAttributes, NoneType]

A JSON:API resource for an upload.

news

Package for the news API.

api

Module that defines the portal api.

endpoints

Package that contains endpoints for news.

news

Module that implements the endpoints for news.

NewsFilterModel

Bases: BaseModel

Define the JSON:API filter for news.

/news_items post

Create a new news item.

/news_items/{id} delete

Delete a new news item.

This api can return the following HTTP codes:

Status Description
404 News Item was not found.
/news_items/{id} get

Get a news item.

/news_items get

Get news items.

/news_items/{id} patch

Update a new news item.

This api can return the following HTTP codes:

Status Description
404 News item was not found.
pages

Package for the pages API.

api

Module for defining the pages API.

endpoints

Package for defining the pages endpoint.

pages

Module for defining the pages endpoint.

PageFilter

Bases: BaseModel

Define the JSON:API filter for pages.

/pages post

Create a page.

/pages/{id} delete

Delete a page.

This api can return the following HTTP codes:

Status Description
404 Page was not found.
/pages/{id} get

Get page.

/pages get

Get pages.

/pages/{id} patch

Update a page.

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.

/applications/{id} get

Get application.

/applications get

Get all applications of kwai.

/applications/{id} patch

Get application.

news

Module that implements news endpoints.

/news get

Get news items for the portal.

Only promoted news items are returned for the portal.

resources

Module that defines common JSON:API resource identifiers.

CountryResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a country.

schemas

Module for defining common JSON:API schemas.

CountryAttributes

Bases: BaseModel

Attributes for the country JSON:API resource.

CountryDocument

Bases: Document[CountryResource, None]

A JSON:API document for one or more countries.

create(country) classmethod

Create a country document from a country value object.

CountryResource

Bases: CountryResourceIdentifier, ResourceData[CountryAttributes, None]

A JSON:API resource for a country.

teams

Package for the teams API.

api

Module that defines the teams API.

TeamMemberFilterModel

Bases: BaseModel

Define the JSON:API filter for team members.

/teams post

Create a new team.

/teams/{id}/members post

Add a member to the team with the given id.

/teams/{id} delete

Delete the team with the given id.

This api can return the following HTTP codes:

Status Description
404 Team not found
/teams/members get

Get all members that can be part of a team.

/teams/{id} get

Get the team with the given id.

/teams/{id}/members get

Get the members of the team with the given id.

/teams get

Get all teams of the club.

/teams/{id} patch

Update an existing team.

This api can return the following HTTP codes:

Status Description
404 Team not found
presenters

Module for defining presenters of the teams api.

JsonApiMembersPresenter

Bases: JsonApiPresenter[TeamMemberDocument], AsyncPresenter[IterableResult[MemberEntity]]

A presenter that transforms an iterator of members into a TeamMember document.

JsonApiTeamMemberPresenter

Bases: JsonApiPresenter[TeamMemberDocument], Presenter[tuple[TeamMember, TeamEntity]]

A presenter that transforms a team member into a JSON:API document.

JsonApiTeamMembersPresenter

Bases: JsonApiPresenter[TeamMemberDocument], Presenter[TeamEntity]

A presenter that transforms team members into a JSON:API document.

JsonApiTeamPresenter

Bases: JsonApiPresenter[TeamDocument], Presenter[TeamEntity]

A presenter that transform a team entity into a JSON:API document.

JsonApiTeamsPresenter

Bases: JsonApiPresenter[TeamDocument], AsyncPresenter[IterableResult[TeamEntity]]

A presenter that transforms an iterator of teams into a JSON:API document.

resources

Module that defines all JSON:API resource identifiers for the team API.

TeamMemberResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a team member.

schemas

Module that defines the schemas for the teams API.

TeamAttributes

Bases: BaseModel

Attributes for the team JSON:API resource.

TeamDocument

Bases: Document[TeamResource, TeamInclude]

A JSON:API document for one or more teams.

create(team) classmethod

Create a team document from a team entity.

TeamMemberAttributes

Bases: BaseModel

Attributes for a team member.

TeamMemberDocument

Bases: Document[TeamMemberResource, TeamMemberInclude]

A JSON:API document for one or more team members.

create(team_member, team=None) classmethod

Create a team member document.

TeamMemberRelationships

Bases: BaseModel

Relationships for a team member JSON:API resource.

TeamMemberResource
TeamRelationships

Bases: BaseModel

Relationships for a team JSON:API resource.

TeamResource

Bases: TeamResourceIdentifier, ResourceData[TeamAttributes, TeamRelationships]

A JSON:API resource for a team.

trainings

Package for the trainings API.

api

Module that defines the trainings API.

endpoints

Package for all endpoints of trainings API.

coaches

Module for defining endpoints for coaches.

/trainings/coaches get

Get coaches.

teams

Module for defining the trainings/teams API.

/trainings/teams get

Get teams.

training_definitions

Module for endpoints for training definitions.

/training_definitions post

Create a new training definition.

/training_definitions/{training_definition_id} delete

Delete a training definition.

This api can return the following HTTP codes:

Status Description
404 Training definition was not found.
/training_definitions/{training_definition_id} get

Get training definition with the given id.

This api can return the following HTTP codes:

Status Description
404 Training definition was not found.
/training_definitions get

Get all training definitions.

/training_definitions/{training_definition_id}/trainings get

Get trainings of the given training definition.

This api can return the following HTTP codes:

Status Description
404 Training definition or coach was not found.
/training_definitions/{training_definition_id} patch

Update a training definition.

This api can return the following HTTP codes:

Status Description
404 Training definition was not found.
trainings

Module for endpoints for trainings.

TrainingsFilterModel

Bases: BaseModel

Define the JSON:API filter for trainings.

/trainings post

Create a new training.

/trainings/{training_id} delete

Delete a training definition.

This api can return the following HTTP codes:

Status Description
404 Training was not found.
/trainings/{training_id} get

Get the training with the given id.

This api can return the following HTTP codes:

Status Description
404 Training was not found.
/trainings get

Get all trainings.

This api can return the following HTTP codes:

Status Description
404 Coach or Training definition was not found.
/trainings/{training_id} patch

Update a training.

This api can return the following HTTP codes:

Status Description
404 Training was not found.
schemas

Package for schemas of the trainings endpoint.

coach

Module that defines the JSON:API schemas for coaches.

CoachAttributes

Bases: BaseModel

Attributes for a coach JSON:API resource.

CoachDocument

Bases: Document[CoachResource, NoneType]

A JSON:API document for one or more coaches.

create(coach) classmethod

Create a document from a coach entity.

CoachResource

Bases: CoachResourceIdentifier, ResourceData[CoachAttributes, NoneType]

A JSON:API resource for a coach.

create(coach) classmethod

Create a JSON:API resource from a coach entity.

team

Module that defines the team schema.

TeamAttributes

Bases: BaseModel

Attributes for a team JSON:API resource.

TeamDocument

Bases: Document[TeamResource, NoneType]

A JSON:API document for one or more teams.

create(team) classmethod

Create a document from a team entity.

TeamResource

Bases: TeamResourceIdentifier, ResourceData[TeamAttributes, NoneType]

A JSON:API resource for a team.

training

Schemas for training(s).

CoachAttributes

Bases: BaseModel

Attributes for a coach JSON:API resource.

CoachResource

Bases: CoachResourceIdentifier, ResourceData[CoachAttributes, NoneType]

A JSON:API resource for a coach.

TrainingAttributes

Bases: BaseModel

Attributes for training JSON:API resource.

TrainingCoach

Bases: BaseModel

Schema for coach/training specific information.

TrainingDocument

Bases: Document[TrainingResource, TrainingInclude]

A JSON:API document for one or more training resources.

create(training) classmethod

Create a training document from a training entity.

TrainingEvent

Bases: BaseModel

Schema for the event information of a training.

TrainingRelationships

Bases: BaseModel

Relationships of a training JSON:API resource.

TrainingResource
TrainingText

Bases: BaseModel

Schema for the content of a training.

training_definition

Module for the training definition schema.

TrainingDefinitionAttributes

Bases: BaseModel

Attributes for a training definition JSON:API resource.

TrainingDefinitionDocument

Bases: Document[TrainingDefinitionResource, TeamResource]

A JSON:API document for one or more training definitions.

create(training_definition) classmethod

Create a document from a training definition entity.

TrainingDefinitionRelationships

Bases: BaseModel

Relationships for a training definition JSON:API resource.

TrainingDefinitionResource

app

Module that creates a FastAPI application for the API and Frontend.

create_app()

Create the FastAPI application for API and frontend.

lifespan(app) async

Log the start/stop of the application.

cli

Package for modules used in the CLI program.

__main__

Module for starting the cli.

commands

Package for all CLI commands.

bus

bus contains subcommands for the event bus.

check()

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

groups_command(stream=typer.Option(help='Name of the stream'), group=typer.Option(default=None, help='Name of the group'), delete=typer.Option(default=False, help='Delete the group?'))

Command for showing groups of a stream.

show_command(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).

Option(False, help='Show the password')
stream_command(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.

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

List all messages or not? Default is False.

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

Command for getting a list of streams from Redis.

Parameters:

Name Type Description Default
groups bool

List all groups of a stream or not? Default is False.

Option(False, help='List all groups')
test_command()

Command for testing the redis connection.

When a connection was successful, a PING command will be sent to the redis server.

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).

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

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

The firstname of the new user

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

The lastname of the new user

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

The password of the new user

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

dependencies

Module that defines dependencies for the CLI program.

configure()

Configure the dependency injection system for the CLI program.

create_database(settings) async

Create the database dependency.

create_redis(settings) async

Create the Redis dependency.

core

Package for all core modules.

args

Module for handling arguments for starting a uvicorn application.

create_args(prog, default_port=8000)

Parse and create cli arguments.

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 property

Return the database settings.

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

begin() async

Start a transaction.

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_affected_rows(rowcount)

Log the number of affected rows of the last executed query.

Parameters:

Name Type Description Default
rowcount int

The number of affected rows.

required
log_query(query)

Log a query.

Parameters:

Name Type Description Default
query str

The query to log.

required
rollback() async

Rollback a transaction.

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 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 property

Return the sql statement of the query.

rows

Module that defines common table classes.

OwnerRow dataclass

Represent the owner data.

create_owner()

Create an Author value object from row data.

OwnerTableRow dataclass

Bases: TableRow

Represent the owner data.

create_owner()

Create an Author value object from row data.

TextRow 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 text

content str

The long content of the text

summary str

A summary of the text

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_text(author)

Create a LocaleText value object from a row.

Parameters:

Name Type Description Default
author Owner

The author of the text.

required
table

Module for the table decorator.

Table

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 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
str

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).

table_row

Module that defines some dataclasses that can be used as data transfer objects.

JoinedTableRow dataclass

A data transfer object for data from multiple tables.

Each field of the dataclass will represent a table. The name of the field will be used as prefix for creating an alias for each column of the associated table.

The derived class must be a dataclass.

Note

The derived class is also the ideal place to act as builder for an entity.

get_aliases() classmethod

Return fields of all the TableRow dataclasses as aliases.

The name of the field will be used as prefix for the alias.

map(row) classmethod

Map all fields of this dataclass to the TableRow dataclasses.

TableRow dataclass

A data transfer object for a row of one table.

The derived class must be a dataclass.

Note

The derived class is also the ideal place to act as builder for an entity.

column(column_name) classmethod

Return the column prefixed with the table name.

field(column_name) classmethod

Call sql-smith field with the given column.

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

get_aliases(prefix=None) classmethod

Return aliases for all the fields of the dataclass.

get_column_alias(name, prefix=None) classmethod

Return the alias for a column.

map(row, prefix=None) classmethod

Map the data of a row to the dataclass.

A ValueError will be raised when a field contains data with the wrong type.

uow

Module that implements a unit of work pattern.

UnitOfWork

A unit of work implementation.

__aenter__() async

Enter the unit of work.

__aexit__(exc_type, exc_val, exc_tb) async

Exit the unit of work.

When an exception occurred, the transaction will be rollbacked.

domain

Package for all common domain modules.

entity

Module that defines a generic entity.

DataclassEntity dataclass

A base class for an entity.

An entity is immutable, so it cannot be modified. A method of an entity that changes the entity must allways return a new entity instance with the changed data. The method replace of dataclasses can be used for this.

Currently, this is a separate class to make it possible to migrate to this new class. In the future, the Entity class will be removed and this class will be renamed to Entity.

By default, id is of type IntIdentifier. Overwrite ID in an entity class if another identifier should be used.

Attributes:

Name Type Description
id ID

The id of the entity.

traceable_time TraceableTime

Keeps track of the creation and update timestamp of the entity.

__eq__(other)

Check if two entities are equal.

An entity equals another entity when the id is the same.

__hash__()

Generate a hash for this entity.

__post_init__()

When is id is not set, a default id is created.

set_id(id_)

Set the id for this entity.

This will raise a ValueError if the id was already set. If you need an entity with the same data but with another id, you should create a new entity with dataclasses.replace and replace the id.

shallow_dict()

Return a dictionary representation of the entity.

Note

This method is not recursive. Use asdict from dataclasses when also nested fields must be returned as a dict.

Entity

A base class for an entity.

id 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 Self

The entity to copy the values from

required
changes Any

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.

presenter

Module for defining a presenter.

AsyncPresenter

Bases: ABC

An interface for an async presenter.

A presenter is used to transform an entity into another object that can be used in a view.

An example: convert to a JSON:API resource for returning the entity in a restful API.

present(use_case_result) abstractmethod async

Present the entity.

This method is responsible for converting the entity.

IterableResult dataclass

A dataclass used to represent a result with multiple entities.

Presenter

Bases: ABC

An interface for a presenter.

A presenter is used to transform an entity into another object that can be used in a view.

An example: convert to a JSON:API resource for returning the entity in a restful API.

present(use_case_result) abstractmethod

Present the entity.

This method is responsible for converting the entity.

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.

EntitiesResult dataclass

Bases: UseCaseResult

A result that returns an iterator for entities and the number of entities.

EntityResult dataclass

Bases: UseCaseResult

A result that returns an entity.

NotFoundResult dataclass

Bases: UseCaseResult

A result that indicates that an entity was not found.

TextCommand dataclass

Input for a text.

UseCaseBrowseResult

Bases: NamedTuple

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

UseCaseResult

Bases: ABC

Base class for a use case result.

to_message() abstractmethod

Return a message from the result.

value_objects

Package for all common value objects.

date

Module for defining a date value object.

Date dataclass

An immutable value object for a date.

This class is a decorator of a pendulum object. See: https://pendulum.eustace.io

day property

Return the day of the date.

month property

Return the month of the date.

past property

Is this date in the past?

year property

Return the year of the date.

__str__()

Return a string representation of the date.

add(**kwargs)

Add time.

create(year, month=1, day=1) classmethod

Create a date with the given year, month and day.

create_from_date(date) classmethod

Create a Date from a datetime.date.

create_from_string(value, format_='YYYY-MM-DD') classmethod

Create a Date from a string.

end_of(unit)

Returns a new date resetting it to the end of the given unit.

get_age(some_date)

Return the age on the given date.

today() classmethod

Return today as date.

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

Abstract and generic class for an identifier.

value 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.

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 property

Return the delta between end and start time.

endless 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.

DocumentFormat

Bases: Enum

Value object for a document format.

Locale

Bases: Enum

Value object for a Locale.

LocaleText dataclass

Value object for text.

Several entities, like news stories, trainings, contain text. This value object represents a text for a certain locale.

Attributes:

Name Type Description
locale Locale

The locale of the content.

format DocumentFormat

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[Locale, 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 Locale

The locale of the content

required

Returns:

Type Description
LocaleText

The content, when available.

Raises:

Type Description
KeyError

when the locale is not 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
Self

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

Self

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 property

Return the delta between end and start time.

Returns: The delta between the start and end time.

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

endless 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.

create_from_string(start, end=None, timezone='UTC') classmethod

Create a time period from one or two strings.

Parameters:

Name Type Description Default
start str

a start time in format 00:00

required
end str | None

an optional end time in format 00:00

None
timezone str

an optional timezone name

'UTC'

Returns:

Type Description
TimePeriod

A new time period.

timestamp

Module that defines a value object for a local timestamp.

Timestamp dataclass

A value object for a timestamp.

The datetime should always be in UTC.

date property

Return the date.

day property

Return the day.

empty property

Return True when the timestamp is unknown.

hours property

Return the hours.

is_past property

Return True when the timestamp in the past.

minutes property

Return the minutes.

month property

Return the month.

posix property

Return the POSIX timestamp.

seconds property

Return the seconds.

time property

Return the date.

year 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
Timestamp Timestamp

A new timestamp with the delta.

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

Create a timestamp from a string.

Parameters:

Name Type Description Default
date_time str | None

The string to convert to a timestamp. None or an empty string will result in an "empty" local timestamp.

None
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_utc(timestamp) classmethod

Create a timestamp from a datetime and make it UTC.

When None is passed, an empty timestamp will be returned.

create_with_delta(**kwargs) classmethod

Create a current local timestamp and applies the delta.

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.

__hash__()

Return a hash value for the unique 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.

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
dependencies

Module that defines the dependencies for events.

create_database(settings=Depends(get_settings)) async

Create the database dependency.

create_mailer(settings=Depends(get_settings))

Create the mailer dependency.

create_template_engine(settings=Depends(get_settings))

Create the template engine dependency.

event

Module that defines the base class Event.

Event dataclass

Base class for all events.

data property

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

EventMeta dataclass

Metadata for the event.

The combination of version, module and name should result in a unique full name in kwai and will be used as name for a Redis stream.

Attributes:

Name Type Description
version str

The version of the event.

module str

The module that the event belongs to (e.g. identity)

name str

The name of the event.

full_name property

Return the full name of the event.

event_router

Module for defining an event router.

EventRouter dataclass

A router that defines which method must be called on an event.

execute(event_data) async

Executes the callback.

fast_stream_publisher

Module for defining a publisher using FastStream.

FastStreamPublisher

Bases: Publisher

A publisher using FastStream.

publisher

Module for defining an interface for a publisher.

A publisher should publish events to an event bus.

Publisher

Interface for a publisher.

publish(event) abstractmethod async

Publish an event.

redis_bus

Module for defining a publisher using Redis.

RedisBus

Bases: Publisher, Subscriber

An event bus using Redis streams.

cancel() async

Cancel all consumers.

run() async

Start all consumers.

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

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 property

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

stream_name 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 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_ str

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_ str

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.

delete_group(group_name) async

Delete the group.

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.

subscriber

Module for defining an interface for a subscriber.

Subscriber

Bases: ABC

Interface for a subscriber.

subscribe(event) abstractmethod

Subscribe to an event with the given task.

functions

Module that defines some common functions.

async_groupby(it, key) async

An async groupby.

generate_filenames(prefix, suffix, places=3)

Generate sequential filenames with the format .

The index field is padded with leading zeroes to the specified number of places

json_api

Module that defines some JSON:API related models.

Document

Bases: BaseModel

A JSON:API document.

resource property

Return the resource of this document.

An assert will occur, when the resource is a list.

resources property

Return the list of resources of this document.

An assert will occur, when the resource is not a list.

__get_pydantic_json_schema__(core_schema, handler) classmethod

Remove included when T_INCLUDE is NoneType.

__repr__()

Return representation of a document.

merge(other)

Merge a document into this document.

When data is not a list yet, it will be converted to a list. When there are included resources, they will be merged into this document. meta is not merged.

serialize(handler)

Remove included and meta when the value is None.

Error

Bases: BaseModel

Defines the model for a JSON:API error.

ErrorSource

Bases: BaseModel

Defines the model for an error source.

JsonApiPresenter

An interface for a presenter that generates a JSON:API document.

get_document()

Return the JSON:API document.

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.

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

Bases: BaseModel

A JSON:API relationship.

ResourceData

Bases: BaseModel

A JSON:API resource.

serialize(handler)

Remove relationships and meta from serialization when the values are none.

ResourceIdentifier

Bases: BaseModel

A JSON:API resource identifier.

__hash__()

Create a hash for a resource.

ResourceMeta

Bases: BaseModel

Meta for a JSON:API resource.

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 property

Return the headers.

html property

Return the HTML content.

recipients property

Return the recipients.

subject property

Return the subject of the mail.

text 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 abstractmethod property

Returns the headers for this message.

html abstractmethod property

Returns the HTML for the message.

recipients abstractmethod property

Returns the recipients for the message.

subject abstractmethod property

Return the subject of the message.

text 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.

AdminApplicationSettings

Bases: ApplicationSettingsModel

Settings for the admin application.

AdminSettings

Bases: BaseModel

Settings for the administrator of the website.

ApplicationSettingsModel

Bases: BaseModel

Settings that apply to all applications.

AuthenticationApplicationSettings

Bases: ApplicationSettingsModel

Settings for the auth application.

AuthorApplicationSettings

Bases: ApplicationSettingsModel

Settings for the author application.

CORSSettings

Bases: BaseModel

Settings for configuring CORS.

ClubApplicationSettings

Bases: ApplicationSettingsModel

Settings for the club application.

CoachApplicationSettings

Bases: ApplicationSettingsModel

Settings for the portal application.

ContactSettings

Bases: BaseModel

Settings for the contact of the club.

DatabaseSettings

Bases: BaseModel

Settings for the database connection.

EmailSettings

Bases: BaseModel

Settings for sending emails.

FilesSettings

Bases: BaseModel

Settings for files (upload).

FrontendSettings

Bases: BaseModel

Settings for the frontend.

LoggerSettings

Bases: BaseModel

Settings for the logger.

PortalApplicationSettings

Bases: ApplicationSettingsModel

Settings for the portal application.

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.

WebsiteSettings

Bases: BaseModel

Settings about the website.

get_settings() cached

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.

jinja2_engine

Modules that implements the template engine interface for jinja2.

Jinja2Engine

Bases: TemplateEngine

Implements the TemplateEngine interface for Jinja2.

web_templates property

Return templates that can be used with a TemplateResponse.

__init__(**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)

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) 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.

events

Package for events.

Subscribe to an event to process the event. One event can have multiple subscribers. Just use a different queue for each subscriber of the same event. Subscribers are triggered by the FastStream application.

A use case is responsible for publishing the events to a broker.

Events are dataclasses.

__main__

Module for starting the event bus.

LoggerMiddleware

Bases: BaseMiddleware

Middleware that adds logging to the event bus.

on_consume(msg) async

Set up a context for the logger.

configure_logger(logger_settings)

Configure the logger.

main() async

Start the event bus.

v1

Package for handling v1 events.

A version is used to handle changes of the event data. When a structure of an event changes, a new version should be created when there are still old events to process.

identity

Module for defining the event router for the identity module.

user_invitation_tasks

Module that defines entry points for tasks for user invitations.

email_user_invitation_task(event, settings=Depends(get_settings), database=Depends(create_database), mailer=Depends(create_mailer), template_engine=Depends(create_template_engine)) async

Task for sending the user invitation email.

user_recovery_tasks

Module that defines entry points for tasks for user recoveries.

email_user_recovery_task(event, settings=Depends(get_settings), database=Depends(create_database), mailer=Depends(create_mailer), template_engine=Depends(create_template_engine)) async

Actor for sending a user recovery mail.

frontend

Package that defines modules for serving the frontend from the Python backend.

app

Module that defines a sub application for handling the frontend.

create_frontend()

Create the frontend.

get_default_app(settings)

Search for the default application in the settings.

apps

Package for defining the routes for all frontend applications.

dependencies

Module for defining dependencies for the frontend applications.

ViteDependency

Vite is a dependency.

__call__(settings)

Create a Vite environment for this application.

etag_file_response

EtagFileResponse

Bases: FileResponse

A FileResponse that will check the etag when if-none-match header is passed.

_generate_etag uses the same implementation as FileResponse. FileResponse automatically sets the etag header with this etag value.

__call__(scope, receive, send) async

Check the etag, and return 304 when the file is not modified.

manifest

Module that defines a class for handling the manifest file of Vite.

Chunk dataclass

An entry of a manifest file.

Manifest

Class for handling a manifest file of Vite.

chunks property

Return the entries.

__init__(entries)

Initialize the Manifest class.

get_chunk(entry_name)

Return the entry with the given name.

has_chunk(entry_name)

Check if the entry exists in the manifest file.

load_from_file(file_path) classmethod

Load the manifest from a file.

load_from_string(content) classmethod

Load the manifest from a string.

vite

Module for defining a class that handles files and assets created with vite.

DevelopmentVite

Bases: Vite

Vite implementation for development.

__init__(server_url)

Initialize the development version of vite.

Parameters:

Name Type Description Default
server_url str

The url for the vite server

required

Note

When vite is configured (see vite.config.ts) with a base then make sure that this base is also part of the server_url. For example: when base is '/apps/author' and the server is running on localhost with port 3001, then server_url should be: 'http://localhost:3001/apps/author'.

ProductionVite

Bases: Vite

Vite implementation for production.

__init__(manifest_filepath, base_path)

Initialize the production Vite runtime.

Parameters:

Name Type Description Default
manifest_filepath Path

Path to the manifest file.

required
base_path Path

Path to the dist folder.

required

Note

base_path is the path where the dist folder of an application is installed For example '/website/frontend/apps/portal' must contain a dist folder.

init(*entries)

Load the manifest file.

Vite

Bases: ABC

Interface for a Vite runtime.

get_asset_path(asset_path) abstractmethod

Return the path for an asset.

None is returned when the file should not be processed. This is the case in the development environment, because Vite will serve the assets.

None should also be returned when the file does not exist in the dist folder. This way, the url path will be handled by Vue Router.

When the path starts with public, the path without 'public' is used to search the file in the dist folder.

get_css(base_url) abstractmethod

Get the css files for the given entries.

get_preloads(base_url) abstractmethod

Get the preloads for the given entries.

get_scripts(base_url) abstractmethod

Get the scripts for the given entries.

init(*entries) abstractmethod

Initialize the Vite runtime for the given entries.

modules

Package for all modules.

club

Package for the club module.

This module implements a bounded context for club information like memberships.

Entities
MemberEntity

A member entity represents a member of the club.

Class documentation: [MemberEntity][kwai.modules.club.members.member.MemberEntity].

domain

Package for entities and value objects.

coach

Module for defining a coach entity.

CoachEntity

Bases: Entity[CoachIdentifier]

A coach entity.

description property

Return the description of the coach.

diploma property

Return the diploma of the coach.

is_active property

Is the coach active?

member property

Return the related member.

name property

Return the name of the coach.

remark property

Return the remark of the coach.

traceable_time property

Return the traceable_time.

user property

Return the related user.

uuid property

Return the uuid of the coach.

__init__(*, id_=None, member, description='', diploma='', active=True, remark='', user=None, traceable_time=None)

Initialize a coach.

Parameters:

Name Type Description Default
id_ CoachIdentifier

The id of the coach.

None
member MemberEntity

A coach is a member of the club.

required
description str

The description (bio) of the coach.

''
diploma str

The diploma of the coach.

''
active bool

Whether the coach is active.

True
remark str

A remark about the coach.

''
user Owner | None

A coach can also be a user of the system.

None
traceable_time TraceableTime | None

The creation and modification timestamp of the coach.

None
contact

Module that defines the contact entity.

ContactEntity

Bases: Entity[ContactIdentifier]

A contact entity.

address property

Return the address.

emails property

Return the emails of the contact.

Note: the returned list is a copy.

mobile property

Return the mobile.

remark property

Return the remark.

tel property

Return the tel.

traceable_time property

Return the traceable_time.

__init__(*, id_=None, emails=None, tel='', mobile='', address, remark='', traceable_time=None)

Initialize the contact entity.

add_email(email)

Add an email to the contact.

remove_email(email)

Remove the email from the contact.

country

Module that defines the Country entity.

CountryEntity

Bases: Entity[CountryIdentifier]

A country entity.

iso_2 property

Return the iso_2.

iso_3 property

Return the iso_3.

name property

Return the name.

__init__(*, id_=None, iso_2, iso_3, name, traceable_time=None)

Initialize the country entity.

Parameters:

Name Type Description Default
id_ CountryIdentifier | None

The identifier of the country.

None
iso_2 str

The ISO 2 code of the country.

required
iso_3 str

The ISO 3 code of the country.

required
name str

The name of the country.

required
traceable_time TraceableTime | None

The creation/modification time of the entity.

None
__str__()

Returns a string representation (iso_2) of the country.

file_upload

Module that defines a file upload entity.

FileUploadEntity

Bases: Entity[FileUploadIdentifier]

An FileUploadEntity keeps information about a file upload.

filename property

Return the filename.

owner property

Return the owner.

preview property

Return the preview.

remark property

Return the remark.

traceable_time property

Return the creation/modification time.

uuid property

Return the uuid.

__init__(*, id_=None, uuid=None, filename, owner, remark='', preview=False, traceable_time=None)

Initialize a file upload entity.

Parameters:

Name Type Description Default
id_ FileUploadIdentifier | None

The id of the upload.

None
uuid UniqueId | None

The unique id of the upload.

None
filename str

The name of the file.

required
owner Owner

The user who uploaded the file.

required
remark str

A remark about the upload.

''
preview bool

Whether the upload is a preview.

False
traceable_time TraceableTime | None

The creation and modification timestamp of the upload.

None
member

Module for defining the Member entity.

MemberEntity

Bases: Entity[MemberIdentifier]

A member entity.

is_active property

Is this member active?

is_competitive property

Is this member participating in competition?

license property

Return the license.

name property

Return the name of the member.

person property

Return the person.

remark property

Return the remark.

traceable_time property

Return the traceable_time.

uuid property

Return the uuid.

__init__(*, id_=None, uuid=None, license, person, remark='', active=True, competition=False, traceable_time=None)

Initialize a member.

Parameters:

Name Type Description Default
id_ MemberIdentifier | None

The id of the member.

None
uuid UniqueId | None

A unique id for the member.

None
license License

The license of the member.

required
person PersonEntity

The related person entity.

required
remark str

A remark about the member.

''
active bool

Is this member still member of the club?

True
competition bool

Is this member participating in competitions?

False
traceable_time TraceableTime | None

The creation and modification timestamp of the training.

None
person

Module that defines an entity for a person.

PersonEntity

Bases: Entity[PersonIdentifier]

A person entity.

birthdate property

Return the birthdate of the person.

contact property

Return the contact.

gender property

Return the gender of the person.

name property

Return the name of the person.

nationality property

Return the nationality.

remark property

Return the remark.

traceable_time property

Return the traceable_time.

__init__(*, id_=None, name, gender, birthdate, nationality, contact, remark='', traceable_time=None)

Initialize a person.

Parameters:

Name Type Description Default
id_ PersonIdentifier | None

The id of the person.

None
name Name

The name of the person.

required
gender Gender

The gender of the person.

required
birthdate Birthdate

The birthdate of the person.

required
nationality CountryEntity

The nationality of the person.

required
contact ContactEntity

The related contact entity.

required
remark str

A remark about the person.

''
traceable_time TraceableTime | None

The creation and modification timestamp of the training.

None
value_objects

Module for defining value objects for the members module.

Address dataclass

An address.

Birthdate dataclass

A birthdate of a person.

age property

Return the age on the current day.

__str__()

Return a string representation of a birthdate.

get_age_in_year(year)

Return the age that will be reached in the given year.

Gender

Bases: Enum

The gender of a person.

License dataclass

A license of a member.

expired property

Is this license expired?

__str__()

Return a string representation of a license.

get_member

Module that implements the use case 'Get Member'.

GetMember

Use case 'Get Member'.

__init__(repo, presenter)

Initialize the use case.

Parameters:

Name Type Description Default
repo MemberRepository

The repository used to get the member.

required
presenter Presenter[MemberEntity]

The presenter used to handle the result of the use case.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetMemberCommand

the input for this use case.

required

Returns:

Type Description
None

The member (if it exists) with the given uuid.

Throws

MemberNotFoundException: raised when the member does not exist.

GetMemberCommand dataclass

The input for the use case 'Get Member'.

Attributes:

Name Type Description
uuid str

The unique id of the member.

get_members

Module that defines the use case 'Get Members'.

GetMembers

Use case get members.

__init__(repo, presenter)

Initialize use case.

Parameters:

Name Type Description Default
repo MemberRepository

The repository for members.

required
presenter AsyncPresenter[IterableResult[MemberEntity]]

The presenter for members.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetMembersCommand

the input for this use case.

required
GetMembersCommand dataclass

Input for the get members 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.

active bool

When true (the default), only return the active members.

license_end_month int

Only return members with a license ending in the given month.

license_end_year int

Only return members with a license ending in the given year.

import_members

Module that implements a use case for importing members.

FailureMemberImportResult dataclass

Bases: MemberImportResult

An import of a member failed.

ImportMembers

Use case for importing members.

__init__(importer, file_upload_repo, member_repo, presenter)

Initialize the use case.

Parameters:

Name Type Description Default
importer MemberImporter

A class that is responsible for importing members from a resource.

required
file_upload_repo FileUploadRepository

A repository for storing the file upload information.

required
member_repo MemberRepository

A repository for managing members.

required
presenter Presenter

A presenter

required
execute(command) async

Execute the use case.

ImportMembersCommand dataclass

Input for the use case "ImportMembers".

MemberImportResult dataclass

Bases: UseCaseResult, ABC

The result of the use case ImportMembers.

OkMemberImportResult dataclass

Bases: MemberImportResult

A successful import of a member.

repositories

Package for all the repositories.

coach_db_repository

Module for defining a coach repository using a database.

CoachDbRepository

Bases: CoachRepository

A coach repository using a database.

coach_repository

Module for defining an interface for a coach repository.

CoachRepository

Bases: ABC

An interface for a coach repository.

create(coach) abstractmethod async

Save a new coach.

delete(coach) abstractmethod async

Delete an existing coach.

contact_db_repository

Module that defines a contact repository for a database.

ContactDbRepository

Bases: ContactRepository

A contact repository for a database.

ContactQueryRow dataclass

Bases: JoinedTableRow

A data transfer object for a Contact query.

create_entity()

Create a Contact entity from a row.

contact_repository

Module that defines an interface for a contact repository.

ContactNotFoundException

Bases: Exception

Raised when the contact cannot be found.

ContactRepository

Bases: ABC

Interface for a contact repository.

create(contact) abstractmethod async

Save a contact entity.

delete(contact) abstractmethod async

Delete a contact entity.

get(id_) abstractmethod async

Get the contact for the given id.

update(contact) abstractmethod async

Update a contact entity.

country_db_repository

Module that implements a country repository with a database.

CountryDbRepository

Bases: CountryRepository

A repository for countries in a database.

country_repository

Module that defines an interface for the country repository.

CountryNotFoundException

Bases: Exception

Raised when the country is not found.

CountryRepository

Bases: ABC

An interface for a country repository.

create(country) abstractmethod async

Save a country in the repository.

delete(country) abstractmethod async

Delete a country from the repository.

get_by_iso_2(iso_2) abstractmethod async

Get a country using the iso2 code of the country.

file_upload_db_repository

Module that implements a FileUploadRepository using a database.

FileUploadDbRepository

Bases: FileUploadRepository

An implementation of a FileUploadRepository using a database.

__init__(database)

Initialize the repository.

Parameters:

Name Type Description Default
database Database

The database for this repository.

required
file_upload_preview_repository

Module that defines a file upload repository that can be used for preview.

FileUploadPreviewRepository

Bases: FileUploadRepository

A file upload repository that can be used for preview.

This implementation doesn't save anything to the database.

file_upload_repository

Module that defines an interface for a file upload repository.

DuplicateMemberUploadedException

Bases: Exception

Raised when the member in current upload is loaded more than once.

FileUploadRepository

Bases: ABC

Interface for an import repository.

An import repository registers file uploads.

create(file_upload) abstractmethod async

Save a fileupload.

Parameters:

Name Type Description Default
file_upload FileUploadEntity

A fileupload to save.

required
is_duplicate(member) abstractmethod

Check if the member was already uploaded with this file upload.

save_member(file_upload, member) abstractmethod async

Save a member imported from the file upload.

Parameters:

Name Type Description Default
file_upload FileUploadEntity

The file upload.

required
member MemberEntity

The member from the file upload.

required

Raises:

Type Description
DuplicateMemberUploadedException

if the member in the file upload is already uploaded.

flemish_member_importer

Module for defining an importer for members of the Flemish Judo Federation.

FlemishMemberImporter

Bases: MemberImporter

A class for importing members of the Flemish Judo Federation.

The import is a csv file.

__init__(filename, owner, country_repo)

Initialize the importer.

Parameters:

Name Type Description Default
filename str

The name of the csv file.

required
owner Owner

The user that started the upload.

required
country_repo CountryRepository

A repository to get the nationality of a member.

required
member_db_query

Module that implements a MemberQuery for a database.

MemberDbQuery

Bases: MemberQuery, DatabaseQuery

A database query for members.

MemberQueryRow dataclass

Bases: JoinedTableRow

A data transfer object for the Member query.

create_entity()

Create a Member entity from a row.

member_db_repository

Module for defining a member repository using a database.

MemberDbRepository

Bases: MemberRepository

A member repository using a database.

__init__(database)

Initialize the repository.

Parameters:

Name Type Description Default
database Database

The database for this repository.

required
member_importer

Module for defining an abstract class for importing member entities.

FailureResult dataclass

Bases: Result

Dataclass for a failed member import.

MemberImporter

Bases: ABC

Abstract class for importing member entities from a file.

__init__(filename, owner, country_repo)

Initialize the importer.

Parameters:

Name Type Description Default
filename str

The name of the csv file.

required
owner Owner

The user that started the upload.

required
country_repo CountryRepository

A repository to get the nationality of a member.

required
create_file_upload_entity(preview)

Create a file upload entity.

import_() abstractmethod

Import member entities.

For each imported (or failed import) of a member, a result will be yielded.

OkResult dataclass

Bases: Result

Dataclass for a successful member import.

Result dataclass

Base dataclass for a result of a member import.

member_query

Module that defines an interface for a Member query.

MemberQuery

Bases: Query, ABC

An interface for a member query.

filter_by_active() abstractmethod

Filter on the active members.

filter_by_id(id_) abstractmethod

Filter on the license of the member.

filter_by_license(license) abstractmethod

Filter on the license of the member.

filter_by_license_date(license_end_month, license_end_year) abstractmethod

Filter on the license expiration date.

filter_by_uuid(uuid) abstractmethod

Filter on the uuid.

member_repository

Module that defines an interface for a Member repository.

MemberNotFoundException

Bases: Exception

Raised when a Member cannot be found.

MemberRepository

Bases: ABC

An interface for a repository of members.

activate_members(upload) abstractmethod async

Activate all members that have been uploaded.

create(member) abstractmethod async

Create a member.

Parameters:

Name Type Description Default
member MemberEntity

The member to save.

required

Returns:

Type Description
MemberEntity

A member entity with an identifier.

create_query() abstractmethod

Create a query for querying members.

deactivate_members(upload) abstractmethod async

Deactivate all members that are not being uploaded.

delete(member) abstractmethod async

Delete a member.

Parameters:

Name Type Description Default
member MemberEntity

The member to delete.

required
get(query=None) abstractmethod async

Return the first returned element of the given query.

Parameters:

Name Type Description Default
query MemberQuery | None

The query to use for getting the first member.

None

Raises:

Type Description
MemberNotFoundException

Raised when the member is not found.

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

Return all members of a given query.

Parameters:

Name Type Description Default
query MemberQuery | None

The query to use for selecting the members.

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
AsyncGenerator[MemberEntity, None]

A member entity.

update(member) abstractmethod async

Update a member.

Parameters:

Name Type Description Default
member MemberEntity

The member to update.

required
person_db_repository

Module that implements a person repository for a database.

PersonDbRepository

Bases: PersonRepository

A person repository for a database.

PersonQueryRow dataclass

Bases: JoinedTableRow

A data transfer object for a Contact query.

create_entity()

Create a Contact entity from a row.

person_repository

Module that defines an interface for a person repository.

PersonNotFoundException

Bases: Exception

Raised when a person cannot be found.

PersonRepository

Bases: ABC

An interface for a person repository.

create(person) abstractmethod async

Save a person entity.

delete(person) abstractmethod async

Delete a person entity.

get(id_) abstractmethod async

Get the person for the given id.

update(person) abstractmethod async

Update a person entity.

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, publisher)

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
publisher Publisher

A publisher 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.

_publisher 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, publisher)

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
publisher Publisher

A publisher 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.

_publisher 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.

tokens

Package for all modules related to tokens.

access_token

Module that defines an access token entity.

AccessTokenEntity dataclass

Bases: DataclassEntity

An access token entity.

Attributes:

Name Type Description
user_account UserAccountEntity

The user account associated with this token.

identifier TokenIdentifier

The actual token.

expiration Timestamp

The expiration timestamp of the token.

revoked bool

Whether the token has been revoked.

expired property

Return true when the access token is expired.

revoke()

Revoke the access token.

Returns:

Type Description
Self

A revoked access token.

AccessTokenIdentifier

Bases: IntIdentifier

Identifier for an 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 dataclass

Bases: DataclassEntity

A refresh token entity.

Attributes:

Name Type Description
access_token AccessTokenEntity

The access token associated with this refresh token.

identifier TokenIdentifier

The actual token.

expiration Timestamp

The expiration timestamp of the token.

revoked bool

Whether the token has been revoked.

expired property

Return True when the token is expired.

revoke()

Revoke the refresh token.

Returns:

Type Description
Self

A revoked refresh token.

RefreshTokenIdentifier

Bases: IntIdentifier

Identifier for a 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

Bases: TableRow

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

Bases: TableRow

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 dataclass

Bases: DataclassEntity

A user invitation entity.

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

Attributes:

Name Type Description
email EmailAddress

The email address that receives the invitation.

name Name

The name of the invited

uuid UniqueId

The unique id to use to validate this invitation.

expired_at Timestamp

The timestamp when the invitation expires.

remark str

A remark about the invitation.

mailed_at Timestamp

The timestamp of sending out the email.

user UserEntity

The user that created the invitation.

confirmed_at Timestamp

The timestamp when the invitation was used.

revoked bool

Is this invitation revoked?

confirmed property

Return True when the invitation was confirmed.

is_expired property

Return True when the invitation is expired.

mailed property

Return True if the email has already been sent.

confirm()

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

Returns:

Type Description
Self

A confirmed user invitation.

mail_sent()

Set the timestamp when the mail has been sent.

Returns:

Type Description
Self

A user invitation with a mail sent timestamp.

UserInvitationIdentifier

Bases: IntIdentifier

Identifier for a user invitation.

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

Bases: TableRow

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

A user invitation entity.

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
Self

A dataclass containing the table row data.

user_recoveries

Package that defines all modules to recover a user.

user_recovery

Module that implements a user recovery entity.

UserRecoveryEntity dataclass

Bases: DataclassEntity

A user recovery entity.

confirmed property

Return True when this user recovery was confirmed.

is_expired property

Return True when the user recovery is expired.

mailed property

Return True if the email has already been sent.

confirm()

Confirm the user recovery.

mail_sent()

Set the timestamp when mail has been sent.

UserRecoveryIdentifier

Bases: IntIdentifier

Identifier for a user recovery entity.

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

Bases: TableRow

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.

users

Package for all modules related to users.

user

Module that implements a User entity.

UserEntity dataclass

Bases: DataclassEntity

A user entity.

create_owner()

Create an owner value object from the user entity.

UserIdentifier

Bases: IntIdentifier

Identifier for a user entity.

user_account

Module that implements a user account entity.

UserAccountEntity dataclass

Bases: DataclassEntity

A user account entity.

Attributes:

Name Type Description
user UserEntity

The associated user entity.

password Password

The password of the user.

logged_in bool

Whether the user is logged in.

last_login Timestamp

Timestamp of the last login.

last_unsuccessful_login Timestamp

Timestamp of the last unsuccessful login.

revoked bool

Whether the user is revoked.

admin bool

Whether the user is an administrator.

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.

UserAccountIdentifier

Bases: IntIdentifier

Identifier for 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

Bases: TableRow

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

Bases: TableRow

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.

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 property

Return True when the application can contain events.

can_contain_news property

Return True when the application can contain news.

can_contain_pages property

Return True when the application can contain pages.

description property

Return the description.

id property

Return the id.

name property

Return the name.

remark property

Return the remark.

short_description property

Return the short description.

title property

Return the title.

traceable_time property

Return the creation/modification timestamp of this application.

weight 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?

events int

does this application can contain events?

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.

create_news_item

Module for defining the use case "Create News Item".

CreateNewsItem

Use case "Create News Item".

__init__(repo, application_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo NewsItemRepository

The repository to create the news item.

required
application_repo ApplicationRepository

The repository to get the application entity.

required
owner Owner

The owner of the news item.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command CreateNewsItemCommand

The input for this use case.

required

Raises:

Type Description
ApplicationNotFoundException

raised when the application does not exist.

create_page

Module for defining the use case "Create Page".

CreatePage

Use case "Create Page".

__init__(repo, application_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo PageRepository

The repository for creating a page.

required
owner Owner

The user that owns the page.

required
application_repo ApplicationRepository

The repository for getting the application.

required
execute(command) async

Executes the use case.

Parameters:

Name Type Description Default
command CreatePageCommand

the input for the use case.

required

Raises:

Type Description
ApplicationNotFoundException

Raised when the application does not exist.

delete_news_item

Module for defining the use case "Delete News Item".

DeleteNewsItem

Use case "Delete Page".

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo NewsItemRepository

A repository for deleting a news item.

required
execute(command) async

Executes the use case.

Parameters:

Name Type Description Default
command DeleteNewsItemCommand

The input for this use case.

required

Raises:

Type Description
NewsItemNotFoundException

when the news item does not exist.

DeleteNewsItemCommand dataclass

Input for the use case "Delete News Item".

delete_page

Module for defining the use case "Delete Page".

DeletePage

Use case "Delete Page".

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo PageRepository

A repository for deleting a page.

required
execute(command) async

Executes the use case.

Parameters:

Name Type Description Default
command DeletePageCommand

The input for this use case.

required

Raises:

Type Description
PageNotFoundException

when the page does not exist.

DeletePageCommand dataclass

Input for the use case "Delete Page".

get_application

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

GetApplication

Implements the use case 'get application'.

__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 GetApplicationCommand

The input for this use case.

required
GetApplicationCommand dataclass

Input for the use case GetApplication.

Attributes:

Name Type Description
id int

The id of the application

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

get_news_item

Module for the use case "Get News Item".

GetNewsItem

Use case "Get News Item".

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo NewsItemRepository

A repository for getting the news item.

required
execute(command) async

Executes the use case.

Parameters:

Name Type Description Default
command GetNewsItemCommand

The input for this use case.

required

Returns: A news item entity.

Raises:

Type Description
NewsItemNotFoundException

When the news item does not exist.

GetNewsItemCommand dataclass

Input for the use case "Get News Item".

get_news_items

Implement the use case: get news items.

GetNewsItems

Implementation of the use case.

Use this use case for getting news items.

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo NewsItemRepository

A repository for getting the news items.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetNewsItemsCommand

The input for this use case.

required

Returns:

Type Description
UseCaseBrowseResult

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

GetNewsItemsCommand dataclass

Input for use case: [GetNewsItems][kwai.modules.news.get_news_items.GetNewsItems].

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 news items that are not activated will be returned.

get_page

Module for the use case "Get Page".

GetPage

Use case "Get Page".

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo PageRepository

A repository to get the page.

required
execute(command) async

Execute the use case.

GetPageCommand dataclass

Input for the use case "Get Page".

get_pages

Module for the use case "Get Pages".

GetPages

Use case "Get Pages".

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo PageRepository

A repository to get pages.

required
execute(command) async

Executes the use case.

GetPagesCommand dataclass

Input for the "Get Pages" use case.

news

Package for all modules related to news.

news_item

Module that defines a news item entity.

NewsItemEntity

Bases: Entity[NewsItemIdentifier]

A news item entity.

application property

Return the application.

is_enabled property

Check if the news item is enabled.

period property

Return the active period of the news item.

promotion property

Return the promotion information of the news item.

remark property

Return the remark.

texts property

Return the text content of the news item.

Remark

The list is a copy

traceable_time property

Return the creation/modification timestamp of this application.

Promotion dataclass

Value object for handling promoted news items.

news_item_db_query

Module that implements a NewsItemQuery for a database.

NewsItemDbQuery

Bases: NewsItemQuery, DatabaseQuery

A database query for news stories.

news_item_db_repository

Module that implements a news item repository for a database.

NewsItemDbRepository

Bases: NewsItemRepository

A news item database repository.

Attributes:

Name Type Description
_database

the database for the repository.

news_item_query

Module for defining an interface for a news item query.

NewsItemQuery

Bases: Query

An interface for a news item query.

filter_by_active() abstractmethod

Add a filter to only return active news items.

An active news item is enabled and is not expired.

filter_by_application(application) abstractmethod

Add a filter to return only news items 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 item id.

Parameters:

Name Type Description Default
id_ NewsItemIdentifier

an id of a news item.

required
filter_by_promoted() abstractmethod

Add a filter to return only the promoted news items.

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 items published in this year.

required
month int | None

Only return news items published in this month.

None

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

filter_by_user(user) abstractmethod

Add a filter to only return news items 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.

news_item_repository

Module that defines an interface for a news item repository.

NewsItemNotFoundException

Bases: Exception

Raised when the news item can not be found.

NewsItemRepository

Bases: ABC

Interface for a news item repository.

create(news_item) abstractmethod async

Create a new news item entity.

Parameters:

Name Type Description Default
news_item NewsItemEntity

The news item to create

required

Returns:

Type Description
NewsItemEntity

The news item entity with an identifier.

create_query() abstractmethod

Create a query for querying news items.

delete(news_item) abstractmethod async

Delete a news item.

Parameters:

Name Type Description Default
news_item NewsItemEntity

The news item to delete.

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

Return all news items of a given query.

Parameters:

Name Type Description Default
query NewsItemQuery | 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[NewsItemEntity]

A list of news items.

get_by_id(id_) abstractmethod async

Get the news item with the given id.

Parameters:

Name Type Description Default
id_ NewsItemIdentifier

The id of the news item.

required

Returns:

Type Description
NewsItemEntity

A news item entity.

update(news_item) abstractmethod async

Update a news item entity.

Parameters:

Name Type Description Default
news_item NewsItemEntity

The news item to update.

required
news_tables

Module that defines all dataclasses for the tables containing stories.

NewsItemRow dataclass

Represent a table row of the news items table.

Attributes:

Name Type Description
id int

the id of the news item

enabled int

is the news item 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 news item

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, texts)

Create a news item entity from a table row.

persist(news_item) classmethod

Persist an entity to row data.

Parameters:

Name Type Description Default
news_item NewsItemEntity

The news item entity to persist.

required
NewsItemTextRow dataclass

Bases: TextRow

Represent a row in the news_contents table.

Attributes:

Name Type Description
news_id int

The id of the news item

persist(news_item, text) classmethod

Persist a content value object to the table.

Parameters:

Name Type Description Default
news_item NewsItemEntity

The news item that contains the content.

required
text LocaleText

The text of a news item.

required
news_item_command

Module that defines common command for create/update news items.

NewsItemCommand dataclass

Common input for the use cases "Create News Items" and "Update News Items".

page_command

Module that defines common command for create/update pages.

PageCommand dataclass

Input for the use case "Create Page".

pages

Package for all modules related to pages.

page

Module that defines the Page entity.

PageEntity

Bases: Entity[PageIdentifier]

A page entity.

application property

Return the application.

enabled property

Return if the page is enabled.

priority property

Return the priority of the page.

remark property

Return the remark.

texts property

Return the content.

traceable_time property

Return the created_at.

__init__(*, id_=None, enabled=False, application, texts, priority, remark, traceable_time=None)

Initialize a page entity.

Parameters:

Name Type Description Default
id_ PageIdentifier | None

The id of the page.

None
enabled bool

Is this page enabled?

False
application ApplicationEntity

The related application.

required
texts list[LocaleText]

The text content of the page.

required
priority int

The priority level of the page.

required
remark str

A remark about the page.

required
traceable_time TraceableTime | None

The create and update time of the page.

None
page_db_query

Module that implements a PageQuery for a database.

PageDbQuery

Bases: PageQuery, DatabaseQuery

A database query for pages.

page_db_repository

Module that implements a page repository for a database.

PageDbRepository

Bases: PageRepository

Page repository for a database.

page_query

Module for defining an interface for a page query.

PageQuery

Bases: Query

An interface for a page query.

filter_by_active() abstractmethod

Add a filter to only return active pages.

filter_by_application(application) abstractmethod

Add a filter to return only pages 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 page id.

Parameters:

Name Type Description Default
id_ PageIdentifier

an id of a page.

required
filter_by_user(user) abstractmethod

Add a filter to only return pages of the given user.

Parameters:

Name Type Description Default
user int | UniqueId

The id or unique id of the user.

required
page_repository

Module that defines an interface for a page repository.

PageNotFoundException

Bases: Exception

Raised when a page can not be found.

PageRepository

Bases: ABC

Interface for a page repository.

create(page) abstractmethod async

Create a new page entity.

Parameters:

Name Type Description Default
page PageEntity

The page to create.

required

Returns:

Type Description
PageEntity

The page entity with an identifier.

create_query() abstractmethod

Create a query for querying pages.

delete(page) abstractmethod async

Delete a page.

Parameters:

Name Type Description Default
page PageEntity

The page to delete.

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

Return all pages of a given query.

Parameters:

Name Type Description Default
query PageQuery | 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[PageEntity]

A list of pages.

get_by_id(id_) abstractmethod async

Get the page with the given id.

Parameters:

Name Type Description Default
id_ PageIdentifier

The id of the page.

required

Returns:

Type Description
PageEntity

A page entity.

update(page) abstractmethod async

Update a page entity.

Parameters:

Name Type Description Default
page PageEntity

The page to update.

required
page_tables

Module for defining all table classes for page.

PageRow dataclass

Represent a table row of the page table.

Attributes:

Name Type Description
id int

the id of the page.

enabled int

is this page enabled?

remark str | None

a remark about the page

application_id int

the link to the application

priority int

the priority of the page

created_at datetime

the timestamp of creation

updated_at datetime | None

the timestamp of the last modification

create_entity(application, content)

Create a page entity from a table row.

persist(page) classmethod

Persist an entity to row data.

Parameters:

Name Type Description Default
page PageEntity

The page to persist.

required
PageTextRow dataclass

Bases: TextRow

Represent a row in the page_contents table.

Attributes:

Name Type Description
page_id int

The id of a page.

persist(page, content) classmethod

Persist a content value object to the table.

Parameters:

Name Type Description Default
page PageEntity

The page that contains the content.

required
content LocaleText

The content of a page.

required
update_application

Module that defines the use case: update an application.

UpdateApplication

Implements the use case 'update an application'.

__init__(application_repo)

Initialize the use case.

Parameters:

Name Type Description Default
application_repo ApplicationRepository

A repository for updating an application.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command UpdateApplicationCommand

The input for this use case.

required
UpdateApplicationCommand dataclass

Input for the use case UpdateApplication.

Attributes:

Name Type Description
id int

The id of the application

update_news_item

Module for implementing the use case "Update News Item".

UpdateNewsItem

Use case for updating a news item.

__init__(repo, application_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo NewsItemRepository

A repository for updating news items.

required
application_repo ApplicationRepository

A repository for getting the application.

required
owner Owner

The owner of the news item.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command UpdateNewsItemCommand

The input for this use case.

required

Raises:

Type Description
NewsItemNotFoundException

When the news item does not exist.

ApplicationNotFoundException

When the application does not exist.

UpdateNewsItemCommand dataclass

Bases: NewsItemCommand

Input for the use case "Update News Item".

update_page

Module for the use case "Update Page".

UpdatePage

Use case for updating a page.

__init__(repo, application_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo PageRepository

A repository for updating pages.

required
application_repo ApplicationRepository

A repository for getting the application.

required
owner Owner

The owner of the page.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command UpdatePageCommand

The input for this use case.

required

Raises:

Type Description
PageNotFoundException

When the page does not exist.

ApplicationNotFoundException

When the application does not exist.

UpdatePageCommand dataclass

Bases: PageCommand

Input for the "Update Page" use case.

teams

Package for the teams module.

create_team

Module that defines the use case 'Create Team'.

CreateTeam

Use case 'Create Team'.

__init__(team_repo, presenter)

Initialize the use case.

Parameters:

Name Type Description Default
team_repo TeamRepository

A repository that creates the team.

required
presenter Presenter[TeamEntity]

A presenter for a team entity.

required
execute(command) async

Executes the use case.

CreateTeamCommand dataclass

Input for the use case 'Create Team'.

create_team_member

Module that defines the use case for creating a team member.

CreateTeamMember

Implements the 'Create Team Member' use case.

__init__(team_repository, member_repository, presenter)

Initialize the use case.

Parameters:

Name Type Description Default
team_repository TeamRepository

A repository for retrieving the team.

required
member_repository MemberRepository

A repository for retrieving the member.

required
presenter Presenter[tuple[TeamMember, TeamEntity]]

A Presenter for processing the result.

required
execute(command) async

Execute the use case.

Raises:

Type Description
TeamNotFoundException

If the team does not exist.

MemberNotFoundException

If the member does not exist.

TeamMemberAlreadyExistException

If the member is already part of the team.

CreateTeamMemberCommand dataclass

Input for the 'Create Team Member' use case.

delete_team

Module that defines the use case "Delete Team".

DeleteTeam

Use case for deleting a team.

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo TeamRepository

A repository for deleting a team.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command DeleteTeamCommand

The input for the use case.

required

Raises:

Type Description
TeamNotFoundException

If the team does not exist.

DeleteTeamCommand dataclass

Input for the use case DeleteTeam.

domain

Package for domain models of the teams module.

team

Module for defining the team entity.

TeamEntity

Bases: Entity[TeamIdentifier]

Entity for a team of the club.

is_active property

Is this team active?

members property

Return the members.

Note: the returned list is a copy.

name property

Return the name of the team.

remark property

Return the remark of the team.

traceable_time property

Return the traceable_time.

__repr__()

Return representation of the team entity.

__str__()

Return string representation of the team entity.

TeamMemberAlreadyExistException

Bases: Exception

Raised when the member is already part of the team.

team_member

Module for defining the team member entity.

MemberEntity

Bases: Entity[MemberIdentifier]

A member entity.

A member entity is an entity which holds specific information of a member that can be used for a member of a team.

birthdate property

Return the birthdate.

gender property

Return the gender.

is_active_in_club property

Return if the member is active.

license property

Return the license.

name property

Return the name.

nationality property

Return the nat.

uuid property

Return the uuid.

__repr__()

Return a representation of this entity.

__str__()

Return a string of this entity.

TeamMember dataclass

Represent a member of a team.

When active is False, it means the member is not active for the team it belongs to.

get_members

Module for defining the use case 'Get Members'.

GetMembers

Implements the use case 'Get Members'.

__init__(member_repository, presenter)

Initialize the use case.

execute(command) async

Execute the use case.

GetMembersCommand dataclass

Input for the use case 'Get Members'.

When in_team is False and a team_id is set, only the members that are not part of that team will be returned.

get_team

Module that implements the use case 'Get Team'.

GetTeam

Implement the use case 'Get Teams'.

__init__(team_repo, presenter)

Initialize the use case.

execute(command) async

Execute the use case.

GetTeamCommand dataclass

Input for the use case 'Get Team'.

get_teams

Module that implements the use case 'Get Teams'.

GetTeams

Implement the use case 'Get Teams'.

__init__(team_repo, presenter)

Initialize the use case.

execute(command) async

Execute the use case.

GetTeamsCommand dataclass

Input for the use case 'Get Teams'.

repositories

Package for the repositories of the teams module.

member_db_repository

Module for defining a team member repository for a database.

MemberDbQuery

Bases: MemberQuery, DatabaseQuery

A team member query for a database.

MemberDbRepository

Bases: MemberRepository

A member repository for a database.

MemberQueryRow dataclass

Bases: JoinedTableRow

A data transfer object for the member query.

create_entity()

Create a team member entity from a row.

member_repository

Module for defining the member repository interface.

MemberNotFoundException

Bases: Exception

Raised when a member does not exist.

MemberQuery

Bases: Query, ABC

An interface for a member query.

filter_by_birthdate(start_date, end_date=None) abstractmethod

Find team members by their birthdate.

filter_by_id(id_) abstractmethod

Find a team member by its id.

filter_by_team(team_id, in_team=True) abstractmethod

Find members that are (not) part of the team.

To get only the members that are not part of the team, set in_team to False.

Parameters:

Name Type Description Default
team_id TeamIdentifier

The id of the team

required
in_team bool

Whether the member should be part of the team

True
filter_by_uuid(uuid) abstractmethod

Find a team member by its uuid.

MemberRepository

Bases: ABC

An interface for a member repository.

create_query() abstractmethod

Create a query for querying team members.

get(query=None) abstractmethod async

Return the first returned element of the given query.

Parameters:

Name Type Description Default
query MemberQuery | None

The query to use for getting the first member.

None

Raises:

Type Description
MemberNotFoundException

If the member is not found.

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

Return all members of the given query.

Parameters:

Name Type Description Default
query MemberQuery | None

The query to use for getting the members.

None
limit int | None

The maximum number of members to return.

None
offset int | None

The offset to use for fetching members.

None

Yields:

Type Description
AsyncGenerator[MemberEntity, None]

A team member entity.

team_db_repository

Module that implements a team repository for a database.

MemberPersonCountryMixin dataclass

Dataclass for a member related row.

create_member_entity()

Create a member entity from a row.

TeamDbQuery

Bases: TeamQuery, DatabaseQuery

A team query for a database.

TeamDbRepository

Bases: TeamRepository

A team repository for a database.

TeamQueryRow dataclass

Bases: MemberPersonCountryMixin, JoinedTableRow

A data transfer object for the team query.

create_entity(rows) classmethod

Create a team entity from a group of rows.

team_member_db_query

Module that defines a database query for team members.

TeamMemberDbQuery

Bases: DatabaseQuery

A database query for getting team members.

fetch_team_members() async

Fetch team members.

A specialized fetch method that already transforms the rows into TeamMember objects.

Returns:

Type Description
dict[TeamIdentifier, list[TeamMember]]

A dictionary that contains the list of team members for each team.

dict[TeamIdentifier, list[TeamMember]]

The key is the identifier of the team.

filter_by_teams(*ids)

Filter by teams.

Only the rows that belong to the teams with the given ids, will be returned.

TeamMemberQueryRow dataclass

Bases: JoinedTableRow

A data transfer object for the team member query.

create_team_member()

Create a team member from a row.

team_repository

Module that defines an interface for a team repository.

TeamNotFoundException

Bases: Exception

Raised when a team cannot be found.

TeamQuery

Bases: Query, ABC

An interface for a team query.

filter_by_id(id_) abstractmethod

Find a team by its id.

TeamRepository

Bases: ABC

An interface for a team repository.

add_team_member(team, member) abstractmethod async

Add a member to a team.

create(team) abstractmethod async

Save a new team.

create_query() abstractmethod

Create a team query.

delete(team) abstractmethod async

Delete a team.

get(query=None) abstractmethod async

Return the first returned element of the given query.

Parameters:

Name Type Description Default
query TeamQuery | None

The query to use for getting the first team.

None

Raises:

Type Description
TeamNotFoundException

If the team cannot be found.

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

Return all teams of the given query.

Parameters:

Name Type Description Default
query TeamQuery | None

The query to use for getting the teams.

None
limit int | None

The maximum number of teams to return.

None
offset int | None

The offset to use for fetching teams.

None

Yields:

Type Description
AsyncGenerator[TeamEntity, None]

A team entity.

update(team) abstractmethod async

Update a team.

update_team

Module that defines the Update Team use case.

UpdateTeam

Use case for updating a team.

__init__(team_repo, presenter)

Initialize the use case.

Parameters:

Name Type Description Default
team_repo TeamRepository

A repository for updating the team.

required
presenter Presenter[TeamEntity]

A presenter for a team entity.

required
execute(command) async

Execute the use case.

Raises:

Type Description
TeamNotFoundException

raise when the team does not exist.

UpdateTeamCommand dataclass

Input for the Update Team use case.

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 property

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

name property

Return the name of the coach.

coach_db_query

Module that defines a database query for coaches.

CoachDbQuery

Bases: DatabaseQuery, CoachQuery

A database query for coaches.

CoachQueryRow dataclass

Bases: JoinedTableRow

A data transfer object for the coach query.

create_entity()

Create a coach entity from a row.

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
create_query()

Create the coach query.

coach_query

Module that defines an interface for a coach query.

CoachQuery

Bases: Query, ABC

Interface for a coach query.

filter_by_active() abstractmethod

Add a filter for the active coaches.

filter_by_id(id_) abstractmethod

Add a filter for a given id.

Parameters:

Name Type Description Default
id_ CoachIdentifier

A coach id.

required
filter_by_ids(*id_) abstractmethod

Add a filter on one or more coach identifiers.

Parameters:

Name Type Description Default
id_ CoachIdentifier

one or more ids of a coach.

()
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.

create_query() abstractmethod

Create a coach query.

get_all(query=None) abstractmethod async

Get all coaches.

Parameters:

Name Type Description Default
query CoachQuery | None

The query to use for getting all coaches.

None

When query is omitted, all coaches will be returned.

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.

()
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

Execute 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.

create_training_definition

Module for the use case "Create Training Definition".

CreateTrainingDefinition

Use case for creating a training definition.

__init__(repo, team_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingDefinitionRepository

The repository used to create the training definition.

required
team_repo TeamRepository

The repository for getting the team.

required
owner Owner

The user that executes this use case.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command CreateTrainingDefinitionCommand

The input for this use case.

required
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.

delete_training_definition

Module for the use case "Delete Training Definition".

DeleteTrainingDefinition

Use case "Delete Training Definition".

When delete_trainings is True, Trainings that are related to this definition, will be. When False, the training will be updated.

__init__(repo, training_repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingDefinitionRepository

A repository for deleting a training definition.

required
training_repo TrainingRepository

A repository for deleting or updating a training(s).

required
execute(command) async

Execute the use case.

Raises:

Type Description
TrainingDefinitionNotFoundException

when the training definition does not exist.

DeleteTrainingDefinitionCommand dataclass

Input for the use case DeleteTrainingDefinition.

get_coaches

Module for defining the use case 'get coaches'.

GetCoaches

Use case for getting coaches.

__init__(coach_repo)

Initialize the use case.

Parameters:

Name Type Description Default
coach_repo CoachRepository

The repository for getting the coaches.

required
execute(command) async

Execute the use case.

GetCoachesCommand dataclass

Input for the use case GetCoaches.

get_teams

Module that defines a use case for getting teams.

GetTeams

Use case for getting teams.

__init__(team_repo)

Initialize the use case.

Parameters:

Name Type Description Default
team_repo TeamRepository

The repository for getting the teams.

required
execute() async

Execute the use case.

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_training_definition

Module that defines the use case "Get Training Definition".

GetTrainingDefinition

Use case for getting a training definition.

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingDefinitionRepository

A repository for getting the training definition.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command GetTrainingDefinitionCommand

The input for this use case.

required

Raises:

Type Description
TrainingDefinitionNotFoundException

raised when the training definition does not exist.

GetTrainingDefinitionCommand dataclass

Input for the use case GetTrainingDefinition.

get_training_definitions

Module that defines the use case "Get Training Definitions".

GetTrainingDefinitions

Use case "Get Training Definitions".

__init__(repo)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingDefinitionRepository

A repository for retrieving training definitions.

required
execute(command) async

Execute the use case.

GetTrainingDefinitionsCommand dataclass

Input for the use case "Get Training Definitions".

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 property

Return the name of the team.

team_db_query

Module that defines a database query for teams.

TeamDbQuery

Bases: DatabaseQuery, TeamQuery

A database query for teams.

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
create_query()

Create the team query.

team_query

Module that defines an interface for a team query.

TeamQuery

Bases: Query, ABC

Interface for a team query.

filter_by_id(id_) abstractmethod

Add a filter for a given id.

Parameters:

Name Type Description Default
id_ TeamIdentifier

A team id.

required
filter_by_ids(*id_) abstractmethod

Add a filter on one or more team identifiers.

Parameters:

Name Type Description Default
id_ TeamIdentifier

one or more ids of a team.

()
team_repository

Module that defines an interface for a team repository.

TeamNotFoundException

Bases: Exception

Raised when a team cannot be found.

TeamRepository

Bases: ABC

Interface for a team repository.

create_query() abstractmethod

Create a query for querying teams.

get_all() abstractmethod async

Get all teams.

get_by_id(id) abstractmethod async

Get the team with the given id.

Parameters:

Name Type Description Default
id TeamIdentifier

An id of a team.

required
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.

training_definition_command

Module that defines the common input for the use cases Training Definitions.

TrainingDefinitionCommand dataclass

Input for the create or update Training Definition 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 property

Return if the training is active or not.

cancelled property

Return if the training is cancelled or not.

coaches property

Return the coaches attached to the training.

Remark

The list is a copy

definition property

Return the related training definition.

id property

Return the id of the training.

location property

Return the location of the training.

period property

Return the period of the training.

remark property

Return the remark.

teams property

Return the teams of the training.

Remark

The list is a copy

texts property

Return the text content of a training.

Remark

The list is a copy.

traceable_time property

Return the traceable time of the training.

__init__(*, id_=None, texts, 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
texts 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.

TrainingCoachQueryRow dataclass

Bases: JoinedTableRow

A data transfer object for the training coach query.

create_coach()

Create a training coach from a row.

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 property

Return True when the training definition is active.

description property

Return the description of the training definition.

id property

Return the id of the training definition.

location property

Return the location of the training definition.

name property

Return the name of the training definition.

owner property

Return the owner of the training definition.

period property

Return the period of the training definition.

remark property

Return the remark of the training definition.

team property

Return the team that is associated with this definition.

traceable_time property

Return the creation/modification timestamp of this training definition.

weekday property

Return the weekday of the training definition.

__init__(*, id_=None, name, description, weekday, period, active=True, location='', remark='', team=None, 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.

''
team TeamEntity | None

A team that is associated with the definition.

None
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 Timestamp

The start date to use for the filter.

required
end Timestamp

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

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.

reset_definition(training_definition, delete=False) abstractmethod async

Reset all trainings of a training definition.

Parameters:

Name Type Description Default
training_definition TrainingDefinitionEntity

The definition to use.

required
delete bool

Delete training or update?

False

When delete is True, trainings will be deleted. When False the definition will be set to None.

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

Bases: TableRow

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.

TrainingDefinitionRow dataclass

Represent a table row of the training definitions table.

create_entity(team, owner)

Create a training definition entity from a table row.

Parameters:

Name Type Description Default
team TeamEntity | None

A team that is associated with the definition.

required
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.

TrainingTextRow dataclass

Bases: TextRow

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
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.

update_training_definition

Module for the use case "Update Training Definition".

UpdateTrainingDefinition

Use case for updating a training definition.

__init__(repo, team_repo, owner)

Initialize the use case.

Parameters:

Name Type Description Default
repo TrainingDefinitionRepository

The repository used to update the training definition.

required
team_repo TeamRepository

A repository for getting the team.

required
owner Owner

The user that executes this use case.

required
execute(command) async

Execute the use case.

Parameters:

Name Type Description Default
command UpdateTrainingDefinitionCommand

The input for this use case.

required

Raises:

Type Description
TrainingDefinitionNotFoundException

when the training definition does not exist.

UpdateTrainingDefinitionCommand dataclass

Bases: TrainingDefinitionCommand

Input for the "Update Training Definition" use case.