Skip to content

Reference

kwai_api

Package for kwai 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

create_app()

Create the FastAPI application for API and frontend.

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.

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

Module that implements an etag response for a file.

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.

schemas

Package that contains all schemas used in the API.

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.

CountryResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a country.

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.

TrainingResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a training.

TrainingScheduleResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a training schedule.

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.

authors

Package for author endpoints.

endpoints

Module for defining endpoints for managing authors.

/authors get

Get all authors.

This api can return the following HTTP codes:

Status Description
200 Ok.
401 Not Authorized.
presenters

Module for defining presenters for JSON:API author documents.

JsonApiAuthorsPresenter

Bases: JsonApiPresenter[AuthorsDocument], AsyncPresenter[IterableResult[AuthorEntity]]

A presenter that transform an iterable list of author entities into a JSON:API document.

schemas

Module for defining schemas for an author resource.

AuthorAttributes

Bases: BaseModel

Attributes for an author.

AuthorDocument

Bases: BaseModel

A JSON:API document for an author entity.

AuthorResource

Bases: AuthorResourceIdentifier

A JSON:API resource for an author.

AuthorResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for an author.

AuthorsDocument

Bases: BaseModel

A JSON:API document for multiple author entities.

cookies

Module that defines methods for handling cookies.

create_cookies(response, refresh_token, settings)

Create cookies for access en refresh token.

delete_cookies(response)

Delete all cookies.

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.

Even when a token could not be found, the cookies will be deleted.

This api can return the following HTTP codes:

Status Description
200 The user is logged out successfully.
/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.
400 The reset code was already used.
403 This request is forbidden.
404 The uniqued id of the recovery could not be found.
422 The user could not be found.
revoked_users

Module that implements endpoints for revoke users.

/revoked_users/{id} delete

Cancel the revocation of the user with the given id.

This api can return the following HTTP codes:

Status Description
200 The revocation was successfully cancelled
401 Not authorized
/revoked_users post

(Un)revoke a user.

This api can return the following HTTP codes:

Status Description
201 User was successfully revoked
400 An invalid request was made
401 Not authorized
sso

Module that defines endpoints for SSO logins.

get_google_sso(settings) async

Google SSO dependency.

/google/callback get

Implement the Google login callback.

/google/login get

Initiate the Google login process.

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.
/invitations/{uuid} post

Recreate a user invitation.

Use this API for resending a user invitation. The existing invitation will expire.

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
users

Module that implement all users endpoints.

post

Create a new user account.

A user account can only be created when a related user invitation is not yet expired.

This api can return the following HTTP codes:

Status Description
201 User account created
400 Wrong or missing user invitation relationship
404 User invitation does not exist
422 Invalid email address or user invitation was invalid
get

Get all user accounts.

This api can return the following HTTP codes:

Status Description
200 Ok.
401 Not Authorized.
validation

Module that defines some endpoints to validate a login.

/validate get

Validate the user.

When the user has an expired access token it will automatically be renewed when the refresh token is still valid.

This api can return the following HTTP codes:

Status Description
200 The access token is still valid.
401 Not authorized.
presenters

Module that defines presenters for the auth api.

JsonApiRevokedUserPresenter

Bases: JsonApiPresenter[RevokedUserDocument], Presenter[UserAccountEntity]

A presenter that transforms a user account entity into a JSON:API document.

The document will be a [RevokedUserDocument].

JsonApiUserAccountPresenter

Bases: JsonApiPresenter[UserAccountDocument], Presenter[UserAccountEntity]

A presenter that transforms a user account entity into a JSON:API document.

JsonApiUserAccountsPresenter

Bases: JsonApiPresenter[UserAccountsDocument], AsyncPresenter[IterableResult[UserAccountEntity]]

A presenter that transform an iterable list of user account entities into a JSON:API document.

JsonApiUserInvitationPresenter

Bases: JsonApiPresenter[UserInvitationDocument], Presenter[UserInvitationEntity]

A presenter that transforms a user invitation into a JSON:API document.

JsonApiUserInvitationsPresenter

Bases: JsonApiPresenter[UserInvitationsDocument], AsyncPresenter[IterableResult[UserInvitationEntity]]

A presenter that transform an iterable list of user account entities into a JSON:API document.

schemas

Package for schemas of the auth API.

resources

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

RevokedUserResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a revoked user account.

UserAccountResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a user account.

revoked_user

Schemas for a revoked user.

RevokedUserAttributes

Bases: BaseModel

Attributes for a revoked user.

RevokedUserDocument

Bases: BaseModel

A JSON:API document for a revoked user.

RevokedUserResource

Bases: RevokedUserResourceIdentifier

A JSON:API resource for a revoked user.

user_account

Schemas for a user account resource.

BaseUserAccountAttributes

Bases: BaseModel

Base attributes for a user account JSON:API resource.

CreateUserAccountAttributes

Bases: BaseUserAccountAttributes

Attributes for creating a user account.

CreateUserAccountDocument

Bases: BaseModel

A specific JSON:API document for creating a user account.

CreateUserAccountRelationships

Bases: BaseModel

Relationships needed for creating a user account.

CreateUserAccountResource

Bases: UserAccountResourceIdentifier

A JSON:API resource for creating a user account.

UserAccountAttributes

Bases: BaseUserAccountAttributes

Attributes of a user account JSON:API resource.

UserAccountDocument

Bases: BaseModel

A JSON:API document for one user account.

UserAccountResource

Bases: UserAccountResourceIdentifier

A JSON:API resource for a user account.

UserAccountsDocument

Bases: BaseModel

A JSON:API document for multiple user accounts.

user_invitation

Schemas for a user invitation resource.

UserInvitationAttributes

Bases: BaseModel

Attributes of a user invitation JSON:API resource.

UserInvitationDocument

Bases: BaseModel

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

UserInvitationResource

Bases: UserInvitationResourceIdentifier

A JSON:API resource of a user invitation.

UserInvitationsDocument

Bases: BaseModel

A JSON:API document for multiple user invitations.

club

Package for the members API.

api

Module that defines the members API.

coaches

Package for the coaches endpoints of the club API.

endpoints

Module for defining endpoints for coaches of the club API.

CoachesFilterModel

Bases: BaseModel

JSON:API filter for coaches.

/coaches post

Create a new coach.

This api can return the following HTTP codes:

Status Description
201 Coach was created.
404 Member is not found.
409 Coach already exists.
422 Data is invalid.
/coaches get

Get all coaches.

/coaches/{coach_id} patch

Update a coach.

This api can return the following HTTP codes:

Status Description
404 Coach was not found.
presenters

Module that defines presenters for the coaches endpoint of the club API.

JsonApiCoachPresenter

Bases: JsonApiPresenter[CoachDocument], Presenter[ClubCoachEntity]

A presenter that transforms a club coach entity into a JSON:API document.

JsonApiCoachesPresenter

Bases: JsonApiPresenter[CoachesDocument], AsyncPresenter[IterableResult[ClubCoachEntity]]

A presenter for transforming an iterator with coaches into a JSON:API document.

JsonApiPublicCoachPresenter

Bases: JsonApiPresenter[PublicCoachDocument], Presenter[ClubCoachEntity]

A presenter that transforms a club coach entity into a JSON:API document.

JsonApiPublicCoachesPresenter

Bases: JsonApiPresenter[PublicCoachesDocument], AsyncPresenter[IterableResult[ClubCoachEntity]]

A presenter for transforming an iterator with coaches into a JSON:API document.

schemas

Module that defines JSON:API schemas for the coaches endpoints.

CoachAttributes

Bases: PublicCoachAttributes

All attributes for the coach JSON:API resource.

CoachDocument

Bases: BaseModel

A JSON:API document for a coach.

CoachRelationships

Bases: BaseModel

Relationships for the coach JSON:API resource.

CoachResource

Bases: PublicCoachResource

A JSON:API resource for a coach.

CoachesDocument

Bases: BaseModel

A JSON:API document for multiple coaches.

PublicCoachAttributes

Bases: BaseModel

Public attributes for the coach JSON:API resource.

PublicCoachDocument

Bases: BaseModel

A public JSON:API document for a coach.

PublicCoachResource

Bases: CoachResourceIdentifier

A public JSON:API resource identifier for a coach.

PublicCoachesDocument

Bases: BaseModel

A public JSON:API document for multiple coaches.

UserAttributes

Bases: BaseModel

Attributes for the user JSON:API resource.

UserResource

Bases: UserResourceIdentifier

A JSON:API resource for a user.

members

Package for the members endpoints of the club API.

endpoints

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.

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

JsonApiContactPresenter

Bases: JsonApiPresenter[ContactDocument], Presenter[ContactEntity]

A presenter that transforms a contact entity into a JSON:API document.

JsonApiMemberPresenter

Bases: JsonApiPresenter[MemberDocument], Presenter[MemberEntity]

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

JsonApiMembersPresenter

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

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

JsonApiPersonPresenter

Bases: JsonApiPresenter, Presenter[PersonEntity]

A presenter that transforms a person entity into a JSON:API document.

JsonApiUploadMemberPresenter

Bases: JsonApiPresenter[MemberUploadDocument], AsyncPresenter[IterableResult[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: BaseModel

A JSON:API document for one contact resource.

ContactRelationships

Bases: BaseModel

Relationships for the contact JSON:API resource.

ContactResource

Bases: ContactResourceIdentifier

A JSON:API resource for a contact.

ContactsDocument

Bases: BaseModel

A JSON:API document for multiple contact resources.

member

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

MemberAttributes

Bases: BaseModel

Attributes for the member JSON:API resource.

MemberDocument

Bases: BaseModel

A JSON:API document for one member resource.

MemberRelationships

Bases: BaseModel

Relationships of a member JSON:API resource.

MemberResource

Bases: MemberResourceIdentifier

A JSON:API resource for a member.

MembersDocument

Bases: BaseModel

A JSON:API document for multiple member resources.

person

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

PersonAttributes

Bases: BaseModel

Attributes for the person JSON:API resource.

PersonDocument

Bases: BaseModel

A JSON:API document for one person.

PersonRelationships

Bases: BaseModel

Relationships of a person JSON:API resource.

PersonResource

Bases: PersonResourceIdentifier

A JSON:API resource for a person.

resources

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

CoachResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a coach.

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.

UserResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a user.

upload

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

MemberUploadAttributes

Bases: BaseModel

Attributes for a file upload of members.

MemberUploadDocument

Bases: BaseModel

A JSON:API document for a file upload of members.

MemberUploadError

Bases: BaseModel

Model for an error occurred during uploading.

MemberUploadRelationships

Bases: BaseModel

Relationships for a resource with file upload of members.

MemberUploadResource

Bases: MemberUploadResourceIdentifier

Resource for a file upload with members.

MemberUploadResourceIdentifier

Bases: ResourceIdentifier

Resource identifier for a file upload of members.

UploadedMemberMeta

Bases: ResourceMeta

Extra meta data for an uploaded member.

UploadedMemberResource

Bases: MemberResource

Member resource with the extra meta data.

news

Package for the news API.

api

Module that defines the portal api.

endpoints

Module that implements the endpoints for /api/v1/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.
422 Invalid data passed.
presenters

Module that defines presenters for the portal/news endpoint.

JsonApiNewsApplicationPresenter

Bases: JsonApiPresenter[NewsApplicationDocument], Presenter[ApplicationEntity]

A presenter that transforms a news application into a JSON:API document.

JsonApiNewsItemPresenter

Bases: JsonApiPresenter[NewsItemDocument], Presenter[NewsItemEntity]

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

JsonApiNewsItemsPresenter

Bases: JsonApiPresenter[NewsItemsDocument], AsyncPresenter[IterableResult[NewsItemEntity]]

A presenter that transfer an iterable list of news items into a JSON:API document.

schemas

Schemas for a news item.

NewsApplicationAttributes

Bases: BaseModel

Attributes of a news application JSON:API resource.

NewsApplicationDocument

Bases: BaseModel

A JSON:API document for a news application.

NewsApplicationResource

Bases: ApplicationResourceIdentifier

A JSON:API resource for a news application.

NewsItemAttributes

Bases: BaseModel

Attributes of a news item JSON:API resource.

NewsItemDocument

Bases: BaseModel

A JSON:API document for a news item resource.

NewsItemRelationships

Bases: BaseModel

Relationships of a news item JSON:API resource.

NewsItemResource

Bases: NewsItemResourceIdentifier

A JSON:API resource for a news item.

NewsItemText

Bases: BaseModel

Schema for the text of a news item.

NewsItemsDocument

Bases: BaseModel

A JSON:API document for multiple news item resources.

pages

Package for the pages API.

api

Module for defining the pages API.

endpoints

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.

presenters

Module that defines presenters for the portal/pages endpoint.

JsonApiPageApplicationPresenter

Bases: JsonApiPresenter[PageApplicationDocument], Presenter[ApplicationEntity]

A presenter that transforms a news application into a JSON:API document.

JsonApiPagePresenter

Bases: JsonApiPresenter[PageDocument], Presenter[PageEntity]

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

JsonApiPagesPresenter

Bases: JsonApiPresenter[PagesDocument], AsyncPresenter[IterableResult[PageEntity]]

A presenter that transfer an iterable list of news items into a JSON:API document.

schemas

Module for defining the page JSON:API resource.

BasePageAttributes

Bases: BaseModel

Basic attributes of a JSON:API page resource.

BasePageText

Bases: BaseModel

Basic schema for the text of a page.

PageApplicationAttributes

Bases: BaseModel

Attributes of a page application JSON:API resource.

PageApplicationDocument

Bases: BaseModel

A JSON:API document for a page application.

PageApplicationResource

Bases: ApplicationResourceIdentifier

A JSON:API resource for a page application.

PageAttributes

Bases: BasePageAttributes

Attributes of a page JSON:API resource.

PageDocument

Bases: BaseModel

A JSON:API document for one page.

PageRelationships

Bases: BaseModel

Relationships of a page JSON:API resource.

PageResource

Bases: PageResourceIdentifier

A JSON:API resource for a page.

PageText

Bases: BasePageText

Schema for the text of a page.

PagesDocument

Bases: BaseModel

A JSON:API document for multiple pages.

portal

Package for the portal API.

api

Module that defines the portal api.

applications

Package for portal/application endpoints.

endpoints

Module that implements applications endpoints.

/applications/{id} get

Get application.

/applications get

Get all applications of kwai.

/applications/{id} patch

Get application.

presenters

Module for defining presenters for api/v1/portal/applications.

JsonApiApplicationPresenter

Bases: JsonApiPresenter[ApplicationDocument], Presenter[ApplicationEntity]

A presenter that transforms an application entity into a JSON:API document.

JsonApiApplicationsPresenter

Bases: JsonApiPresenter[ApplicationsDocument], AsyncPresenter[IterableResult[ApplicationEntity]]

A presenter that transforms an iterable list of applications into a JSON:API document.

schemas

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.

ApplicationBaseResource

Bases: ApplicationResourceIdentifier

A JSON:API resource for an application with only the basic attributes.

ApplicationDocument

Bases: BaseModel

A JSON:API document for one or more applications.

ApplicationResource

Bases: ApplicationResourceIdentifier

A JSON:API resource for an application.

ApplicationsDocument

Bases: BaseModel

A JSON:API document for multiple applications.

coaches

Package that defines public portal api's for coaches.

endpoints

Module that defines the coaches endpoints for the portal API.

/coaches get

Get all active coaches.

presenters

Module that defines presenters for creating JSON:API resources for one or more coaches.

JsonApiCoachesPresenter

Bases: JsonApiPresenter[CoachesDocument], AsyncPresenter[IterableResult[ClubCoachEntity]]

A presenter that transforms an iterable of coaches into a JSON:API document.

schemas

Module that defines schema's for JSON:API structures for one or more coaches.

CoachAttributes

Bases: BaseModel

Attributes for a coach.

CoachResource

Bases: CoachResourceIdentifier

A JSON:API resource for a coach.

CoachesDocument

Bases: BaseModel

A JSON:API document for multiple coaches.

news

Package for portal/news endpoints.

endpoints

Module for defining endpoints for portal/news.

/news get

Get news items for the portal.

Only promoted news items are returned for the portal.

presenters

Module that defines presenters for the portal/news endpoint.

JsonApiNewsItemPresenter

Bases: JsonApiPresenter[NewsItemDocument], Presenter[NewsItemEntity]

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

JsonApiNewsItemsPresenter

Bases: JsonApiPresenter[NewsItemsDocument], AsyncPresenter[IterableResult[NewsItemEntity]]

A presenter that transfer an iterable list of news items into a JSON:API document.

schemas

Module that defines schemas for the portal/news endpoint.

NewsApplicationAttributes

Bases: BaseModel

Attributes of an application JSON:API resource of a news item.

NewsApplicationResource

Bases: ApplicationResourceIdentifier

A JSON:API resource for an application of a news item.

NewsItemAttributes

Bases: BaseModel

Attributes of a news item JSON:API resource.

NewsItemDocument

Bases: BaseModel

A document for one JSON:API news item resource.

NewsItemRelationships

Bases: BaseModel

Relationships of a news item JSON:API resource.

NewsItemResource

Bases: NewsItemResourceIdentifier

A JSON:API resource for a news item.

NewsItemText

Bases: BaseModel

Schema for the text of a news item.

NewsItemsDocument

Bases: BaseModel

A document for multiple JSON:API news item resources.

trainings

Package for the portal trainings API.

endpoints

Module for the endpoints of the portal trainings API.

TrainingsFilterModel

Bases: BaseModel

Define the JSON:API filter for trainings.

/trainings get

Get all trainings for the portal.

This api can return the following HTTP codes:

Status Description
404 Training schedule was not found.
presenters

Presenters for the portal trainings API.

JsonApiTrainingPresenter

Bases: JsonApiPresenter[TrainingDocument], Presenter[TrainingEntity]

A presenter that transforms a training entity into a JSON:API document.

JsonApiTrainingsDocumentPresenter

Bases: JsonApiPresenter[TrainingsDocument], AsyncPresenter[IterableResult[TrainingEntity]]

A presenter for transforming an iterator with trainings into a JSON:API document.

schemas

Schemas for the portal trainings API.

TeamAttributes

Bases: BaseModel

Attributes for a team JSON:API resource.

TeamDocument

Bases: BaseModel

A JSON:API document for one training team.

TeamResource

Bases: TeamResourceIdentifier

A JSON:API resource for a team.

TeamsDocument

Bases: BaseModel

A JSON:API document for multiple training teams.

TrainingAttributes

Bases: BaseModel

Attributes for training JSON:API resource.

TrainingDocument

Bases: BaseModel

A JSON:API document for one training resource.

TrainingEvent

Bases: BaseModel

Schema for the event information of a training.

TrainingRelationships

Bases: BaseModel

Relationships of a training JSON:API resource.

TrainingResource

Bases: TrainingResourceIdentifier

A JSON:API resource for a training.

TrainingScheduleAttributes

Bases: BaseModel

Schema for training schedule attributes linked to a training.

TrainingScheduleDocument

Bases: BaseModel

Document for a training schedule linked to a training.

TrainingScheduleResource

Bases: TrainingScheduleResourceIdentifier

Schema for a training schedule resource linked to a training.

TrainingText

Bases: BaseModel

Schema for the content of a training.

TrainingsDocument

Bases: BaseModel

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

presenters

Module for defining presenters for common entities.

JsonApiCountryPresenter

Bases: JsonApiPresenter[CountryDocument], Presenter[CountryEntity]

A presenter that transforms a country entity into a JSON:API document.

schemas

Module for defining common JSON:API schemas.

ApplicationAttributes

Bases: BaseModel

Attributes of an application JSON:API resource.

ApplicationResource

Bases: ApplicationResourceIdentifier

A JSON:API resource for an application.

CountryAttributes

Bases: BaseModel

Attributes for the country JSON:API resource.

CountryDocument

Bases: BaseModel

A JSON:API document for one or more countries.

CountryResource

Bases: CountryResourceIdentifier

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[TeamMembersDocument], AsyncPresenter[IterableResult[MemberEntity]]

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

JsonApiTeamMemberPresenter

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

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

JsonApiTeamMembersPresenter

Bases: JsonApiPresenter[TeamMembersDocument], 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[TeamsDocument], 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: BaseModel

A JSON:API document for one team.

TeamMemberAttributes

Bases: BaseModel

Attributes for a team member.

TeamMemberDocument

Bases: BaseModel

A JSON:API document for one team member.

TeamMemberRelationships

Bases: BaseModel

Relationships for a team member JSON:API resource.

TeamMemberResource

Bases: TeamMemberResourceIdentifier

A JSON:API resource for a team member.

TeamMembersDocument

Bases: BaseModel

A JSON:API document for multiple team members.

TeamRelationships

Bases: BaseModel

Relationships for a team JSON:API resource.

TeamResource

Bases: TeamResourceIdentifier

A JSON:API resource for a team.

TeamsDocument

Bases: BaseModel

A JSON:API document for multiple teams.

training_schedules

Package for the training_schedules endpoint.

endpoints

Module for endpoints for training schedules.

/training_schedules post

Create a new training schedule.

/training_schedules/{training_schedule_id} delete

Delete a training schedule.

This api can return the following HTTP codes:

Status Description
404 Training schedule was not found.
/training_schedules/{training_schedule_id} get

Get training schedule with the given id.

This api can return the following HTTP codes:

Status Description
404 Training schedule was not found.
/training_schedules get

Get all training schedules.

/training_schedules/{training_schedule_id}/trainings get

Get trainings of the given training schedule.

This api can return the following HTTP codes:

Status Description
404 Training schedule or coach was not found.
/training_schedules/{training_schedule_id} patch

Update a training schedule.

This api can return the following HTTP codes:

Status Description
404 Training schedule was not found.
presenters

Module that defines presenters for the training_schedules endpoint.

JsonApiTrainingSchedulePresenter

Bases: JsonApiPresenter[TrainingScheduleDocument], Presenter[TrainingScheduleEntity]

A presenter for transforming a training schedule entity into a JSON:API document.

JsonApiTrainingSchedulesPresenter

Bases: JsonApiPresenter[TrainingSchedulesDocument], AsyncPresenter[IterableResult[TrainingScheduleEntity]]

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

schemas

Module for the JSON:API representation of a training schedule.

CoachAttributes

Bases: BaseModel

Attributes for a coach linked to a training schedule.

CoachResource

Bases: CoachResourceIdentifier

A JSON:API resource for a coach linked to a training schedule.

TeamAttributes

Bases: BaseModel

Attributes for a team JSON:API resource.

TeamResource

Bases: TeamResourceIdentifier

A JSON:API resource for a team.

TrainingScheduleAttributes

Bases: BaseModel

Attributes for a training schedule JSON:API resource.

TrainingScheduleDocument

Bases: BaseModel

A JSON:API document for one training schedule.

TrainingScheduleRelationships

Bases: BaseModel

Relationships for a training schedule JSON:API resource.

TrainingScheduleResource

Bases: TrainingScheduleResourceIdentifier

A JSON:API resource for a training schedule.

TrainingSchedulesDocument

Bases: BaseModel

A JSON:API document for multiple training schedules.

trainings

Package for the trainings API.

api

Module that defines the trainings API.

coaches

Package for /api/v1/trainings/coaches.

endpoints

Module for defining endpoints for coaches.

/trainings/{training_id}/coaches post

Add a coach to the training.

This api can return the following HTTP codes:

Status Description
404 Training was not found
/trainings/{training_id}/coaches/{coach_id} delete

Remove a coach from a training.

This api can return the following HTTP codes:

Status Description
404 Training was not found.
/trainings/coaches get

Get coaches.

/trainings/{training_id}/coaches get

Get the coaches of a training.

This api can return the following HTTP codes:

Status Description
404 Training was not found
presenters

Module that defines presenters for the trainings/coaches endpoints.

JsonApiCoachesPresenter

Bases: JsonApiPresenter[CoachesDocument], AsyncPresenter[IterableResult[CoachEntity]]

A presenter that transforms an iterable of coaches into a JSON:API document.

JsonApiTrainingCoachesPresenter

Bases: JsonApiPresenter[TrainingCoachesDocument], Presenter[TrainingEntity]

A presenter that transforms an iterable of coaches of a training into a JSON:API document.

schemas

Module that defines the JSON:API schemas for coaches.

BaseTrainingCoachAttributes

Bases: BaseModel

Base attributes for a training coach JSON:API resource.

CoachAttributes

Bases: BaseModel

Attributes for a coach JSON:API resource.

CoachDocument

Bases: BaseModel

A JSON:API document for one coaches.

CoachResource

Bases: CoachResourceIdentifier

A JSON:API resource for a coach.

CoachesDocument

Bases: BaseModel

A JSON:API document for multiple coaches.

CreateTrainingCoachDocument

Bases: BaseModel

A document for creating a training coach.

CreateTrainingCoachResource

Bases: TrainingCoachResourceIdentifier

A resource for creating a training coach.

TrainingCoachAttributes

Bases: BaseTrainingCoachAttributes, CoachAttributes

Attributes for a training coach JSON:API resource.

TrainingCoachDocument

Bases: BaseModel

Document for a coach of a training.

TrainingCoachResource

Bases: TrainingCoachResourceIdentifier

Resource for a training coach JSON:API resource.

TrainingCoachResourceIdentifier

Bases: ResourceIdentifier

A JSON:API resource identifier for a training coach.

TrainingCoachesDocument

Bases: BaseModel

Document for multiple training coaches.

endpoints

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

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

Module for defining presenters for the /api/v1/trainings endpoints.

JsonApiTrainingPresenter

Bases: JsonApiPresenter[TrainingDocument], Presenter[TrainingEntity]

A presenter that transforms a training entity into a JSON:API document.

JsonApiTrainingsDocumentPresenter

Bases: JsonApiPresenter[TrainingsDocument], AsyncPresenter[IterableResult[TrainingEntity]]

A presenter for transforming an iterator with trainings into a JSON:API document.

schemas

Schemas for training(s).

TrainingAttributes

Bases: BaseModel

Attributes for training JSON:API resource.

TrainingDocument

Bases: BaseModel

A JSON:API document for one training resource.

TrainingEvent

Bases: BaseModel

Schema for the event information of a training.

TrainingRelationships

Bases: BaseModel

Relationships of a training JSON:API resource.

TrainingResource

Bases: TrainingResourceIdentifier

A JSON:API resource for a training.

TrainingScheduleAttributes

Bases: BaseModel

Schema for training schedule attributes linked to a training.

TrainingScheduleDocument

Bases: BaseModel

Document for a training schedule linked to a training.

TrainingScheduleResource

Bases: TrainingScheduleResourceIdentifier

Schema for a training schedule resource linked to a training.

TrainingText

Bases: BaseModel

Schema for the content of a training.

TrainingsDocument

Bases: BaseModel

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

teams

Package for the api/v1/trainings/teams endpoints.

endpoints

Module for defining the trainings/teams API.

/trainings/{training_id}/teams post

Add a team to the training.

This api can return the following HTTP codes:

Status Description
404 Training was not found.
/trainings/{training_id}/teams/{team_id} delete

Add a team to the training.

This api can return the following HTTP codes:

Status Description
404 Training was not found.
/trainings/teams get

Get teams.

/trainings/{training_id}/teams get

Get the teams of the training.

This api can return the following HTTP codes:

Status Description
404 Training was not found.
presenters

Module for presenters of the /api/v1/trainings endpoint.

JsonApiTrainingTeamPresenter

Bases: JsonApiPresenter[TeamDocument], Presenter[TeamEntity]

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

JsonApiTrainingTeamsPresenter

Bases: JsonApiPresenter[TeamsDocument], Presenter[TrainingEntity]

A presenter that transforms the teams of a training into a JSON:API document.

schemas

Module that defines the team schema.

TeamAttributes

Bases: BaseModel

Attributes for a team JSON:API resource.

TeamDocument

Bases: BaseModel

A JSON:API document for one training team.

TeamResource

Bases: TeamResourceIdentifier

A JSON:API resource for a team.

TeamsDocument

Bases: BaseModel

A JSON:API document for multiple training teams.

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

kwai_events

Package for events.

Subscribe to an event to process the event. One event can have multiple subscribers.

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

Events are dataclasses.

__main__

Module for defining the event application.

configure_logger(logger_settings)

Configure the logger.

main(settings) async

Main program.

shutdown(sig, frame)

A signal has been received to stop the application.

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, database, mailer, 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, database, mailer, template_engine) async

Actor for sending a user recovery mail.

kwai_core

Package for all kwai_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][kwai.kwai_core.db.database_query.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, id_column='id') 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
id_column str

The name of the id column (default is 'id')

'id'

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, id_column='id') 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

()
id_column str

The name of the id column (default is 'id')

'id'

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, id_column='id') 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
id_column str

The name of the id column (default is 'id').

'id'

Raises:

Type Description
QueryException

Raised when the query contains an error.

Returns:

Type Description
int

The number of rows affected.

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

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

search(column_name) classmethod

Call sql-smith search with the given column.

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

unwrap(val)

Assert when the value is None.

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 and always_commit is False, the transaction will be rollbacked.

__init__(database, *, always_commit=False)

Initialize the unit of work.

When always_commit is True, the unit of work will always be committed, even when an exception occurred.

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.

exceptions

Module that defines domain exceptions.

NotAllowedException

Bases: Exception

Raised when something is not allowed.

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.

CountIterableAsyncPresenter

Bases: AsyncPresenter[IterableResult[T]]

A presenter that counts the number of entries in the use case result.

This presenter can be used in tests.

count property

Return count.

present(use_case_result) async

Process the result of the use case.

EntityPresenter

Bases: Presenter[T]

A simple presenter that stores the entity it receives.

entity property

Return the entity.

present(entity)

It just stores the received 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.

UniqueIdIdentifier

Bases: Identifier[UniqueId]

Class that implements an identifier with a UniqueId.

__repr__()

Return a string representation of the identifier.

is_empty()

This identifier type is never empty.

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.

configure()

Configure the dependency injection system.

Note: only use dependency injection for injecting dependencies into tasks. A task method is used as entry from outside. DI makes it possible to pass dependencies to this method. Regular constructors should be used for injecting dependencies into domain classes.

create_database(settings) async

Create the database dependency.

create_mailer(settings)

Create the mailer dependency.

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

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.

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

The number of actual resources

offset int

The offset of the returned resources (pagination)

limit int

The maximum number of returned resources (pagination)

A limit of 0, means there was no limit 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

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

limit int

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

Relationship

Bases: BaseModel

A JSON:API relationship.

RelationshipList

Bases: BaseModel

A JSON:API relationship that is a list.

ResourceIdentifier

Bases: BaseModel

A JSON:API resource identifier.

__hash__()

Create a hash for a resource.

serialize_id(id_, _info)

When id is serialized, check that it is not None.

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.

GoogleSSOSettings

Bases: BaseModel

Settings for Google SSO.

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

sql_smith

QueryFactory

Factory class for creating queries

delete(table)

Create a DELETE query

insert(table, column_values=None)

Create an INSERT query

select(*columns)

Create a SELECT query

select_distinct(*columns)

Create a SELECT DISTINCT query

update(table, value_set=None)

Create an UPDATE query

capability

HasLimitMixin

is_limited property

Returns True when the query has a LIMIT.

HasOffsetMixin

has_offset property

Return True when the query has an offset.

HasWhereMixin

has_where property

Return True when there is a WHERE clause set to this query.

has_limit

HasLimitMixin
is_limited property

Returns True when the query has a LIMIT.

has_offset

HasOffsetMixin
has_offset property

Return True when the query has an offset.

has_where

HasWhereMixin
has_where property

Return True when there is a WHERE clause set to this query.

engine

BasicEngine

Bases: EngineInterface

Basic engine

A default implementation of an engine.

escape_identifier(identifier)

Escapes an identifier.

The default implementation returns the identifier as is.

escape_like(parameter)

Escapes the LIKE argument

A backslash is used to escape wildcards. Standard wildcards are underscore and percent sign.

export_parameter(param)

Export a parameter.

A boolean will be exported as true or false. A None value will be exported as NULL.

extract_params()

Create a lambda to extract parameters.

extract_sql()

Create a lambda to extract SQL.

flatten_params(*args)

Create a tuple with all parameters found.

flatten_sql(separator, *args)

Transform StatementInterface arguments to a string.

make_delete()

Creates a DeleteQuery.

make_insert()

Creates an InsertQuery.

make_select()

Creates a SelectQuery.

make_update()

Creates an UpdateQuery.

CommonEngine

Bases: BasicEngine

An engine that supports common SQL standard.

escape_identifier(identifier)

Escapes identifiers by putting quotes around it.

MysqlEngine

Bases: BasicEngine

A custom engine for MySQL SQL dialect.

escape_identifier(identifier)

Escapes the identifier by surrounding it with backticks.

make_insert()

Creates a custom MySql INSERT query.

The MySQL insert query supports IGNORE.

make_select()

Creates a custom MySql SELECT query.

The MySQL select query supports SQL_CALC_FOUND_ROWS.

PostgresEngine

Bases: CommonEngine

A custom engine for Postgres SQL dialect.

make_insert()

Creates a custom Postgres INSERT query.

The Postgres insert query supports RETURNING.

make_update()

Creates a custom Postgres INSERT query.

The Postgres update query supports RETURNING.

SqlServerEngine

Bases: BasicEngine

A custom engine for SQL Server SQL dialect.

escape_identifier(identifier)

Escapes identifiers with brackets.

escape_like(parameter)

Escape like argument.

Also escapes character ranges.

make_delete()

Creates a custom SQL Server DELETE query.

SQL Server handles LIMIT differently.

make_select()

Creates a custom SQL Server SELECT query.

SQL Server handles OFFSET and LIMIT differently.

SqliteEngine

Bases: BasicEngine

A custom engine for Sqlite SQL dialect.

export_parameter(param)

Export a parameter.

SQLite doesn't support boolean storage class. True is translated to 1, False to 0.

basic_engine

BasicEngine

Bases: EngineInterface

Basic engine

A default implementation of an engine.

escape_identifier(identifier)

Escapes an identifier.

The default implementation returns the identifier as is.

escape_like(parameter)

Escapes the LIKE argument

A backslash is used to escape wildcards. Standard wildcards are underscore and percent sign.

export_parameter(param)

Export a parameter.

A boolean will be exported as true or false. A None value will be exported as NULL.

extract_params()

Create a lambda to extract parameters.

extract_sql()

Create a lambda to extract SQL.

flatten_params(*args)

Create a tuple with all parameters found.

flatten_sql(separator, *args)

Transform StatementInterface arguments to a string.

make_delete()

Creates a DeleteQuery.

make_insert()

Creates an InsertQuery.

make_select()

Creates a SelectQuery.

make_update()

Creates an UpdateQuery.

common_engine

CommonEngine

Bases: BasicEngine

An engine that supports common SQL standard.

escape_identifier(identifier)

Escapes identifiers by putting quotes around it.

mysql_engine

MysqlEngine

Bases: BasicEngine

A custom engine for MySQL SQL dialect.

escape_identifier(identifier)

Escapes the identifier by surrounding it with backticks.

make_insert()

Creates a custom MySql INSERT query.

The MySQL insert query supports IGNORE.

make_select()

Creates a custom MySql SELECT query.

The MySQL select query supports SQL_CALC_FOUND_ROWS.

postgres_engine

PostgresEngine

Bases: CommonEngine

A custom engine for Postgres SQL dialect.

make_insert()

Creates a custom Postgres INSERT query.

The Postgres insert query supports RETURNING.

make_update()

Creates a custom Postgres INSERT query.

The Postgres update query supports RETURNING.

sql_server_engine

SqlServerEngine

Bases: BasicEngine

A custom engine for SQL Server SQL dialect.

escape_identifier(identifier)

Escapes identifiers with brackets.

escape_like(parameter)

Escape like argument.

Also escapes character ranges.

make_delete()

Creates a custom SQL Server DELETE query.

SQL Server handles LIMIT differently.

make_select()

Creates a custom SQL Server SELECT query.

SQL Server handles OFFSET and LIMIT differently.

sqlite_engine

SqliteEngine

Bases: BasicEngine

A custom engine for Sqlite SQL dialect.

export_parameter(param)

Export a parameter.

SQLite doesn't support boolean storage class. True is translated to 1, False to 0.

functions

alias(field_name, field_alias)

Create an alias for a column or a function.

alias('users.id', 'uid') # "users"."id" AS "uid"

criteria(pattern, *args)

Create a criteria.

c = criteria( "{} = {}", func( 'YEAR', identify('start_date') ), literal(2021) ) # YEAR("start_date") = 2021

express(pattern, *args)

Create an expression.

express('{} + 1', identify('visit')) # "visit" + 1

field(name)

Starts a criteria for a column. Use it to create a condition.

field('users.id').eq(100) # "users".id = ?

func(function, *args)

Create a function.

func('COUNT', 'user.id') # COUNT("users"."id")

group(c)

Create a group of criteria.

group( field('username').eq('tom') .or_(field('first_name').eq('Tom')) ).and_( field('is_active').eq(1) )

("username" = ? OR "first_name" = ?) AND "is_active" = ?

identify(name)

Identify a name.

identify('users.id') # "users"."id"

identify_all(*names)

Identify all names.

identify_all('id', 'username') # ("id", "username")

listing(values, separator=', ')

Create a listing.

listing((1, 1, 2, 3, 5)) # ?, ?, ?, ?, ? listing(identify_all('id', 'username', 'email')) # "id", "username", "email"

literal(value)

Create a literal.

on(left, right)

Create an on clause.

order(column, direction=None)

Create an order clause.

param(value)

Create a parameter.

func('POINT', param(1), param(2)) # POINT(? , ?)

search(name)

Start a LIKE clause.

search('username').contains('admin') # "username" LIKE '%admin%'

query

AbstractQuery

Bases: QueryInterface

Base class for queries.

compile()

Compiles the query and returns the Query object

DeleteQuery

Bases: HasFromMixin, HasWhereMixin, HasLimitMixin, AbstractQuery

Implements the DELETE query.

InsertQuery

Bases: AbstractQuery

Implements the INSERT query.

columns(*columns)

Sets the columns to insert.

into(table)

Sets the table.

map(column_values)

Maps a dictionary to columns and values.

values(*values)

Appends values.

Query

The result of a compile.

params property

Returns all parameters of the SQL statement.

sql property

Returns the compiled SQL statement as a string.

SelectQuery

Bases: CanUnionMixin, HasFromMixin, HasOrderByMixin, HasWhereMixin, HasLimitMixin, HasOffsetMixin, AbstractQuery

Implements a SELECT query.

add_columns(*columns)

Add columns to the selection.

columns(*columns)

Set the columns to select.

distinct(state=True)

Add or remove DISTINCT.

full_join(table, criteria)

Add a FULL join.

group_by(*columns)

Add a GROUP BY clause.

having(criteria)

Add an HAVING clause.

inner_join(table, criteria)

Add an INNER join.

join(table, criteria, join_type='')

Add a join.

left_join(table, criteria)

Add a LEFT join.

right_join(table, criteria)

Add a RIGHT join.

with_(name=None, query=None, recursive=False)

Add a query as CTE.

When no name and query is passed, all CTE's for this query will be removed. When no query is passed, the CTE with the given name will be removed.

UnionQuery

Bases: CanUnionMixin, HasOrderByMixin, AbstractQuery

Implements a union query.

all(state=True)

Sets ALL.

UpdateQuery

Bases: HasWhereMixin, AbstractQuery

Implements an UPDATE query.

set(value_dict)

Sets the column and values with a dictionary.

table(table)

Sets the table.

abstract_query

AbstractQuery

Bases: QueryInterface

Base class for queries.

compile()

Compiles the query and returns the Query object

delete_query

DeleteQuery

Bases: HasFromMixin, HasWhereMixin, HasLimitMixin, AbstractQuery

Implements the DELETE query.

insert_query

InsertQuery

Bases: AbstractQuery

Implements the INSERT query.

columns(*columns)

Sets the columns to insert.

into(table)

Sets the table.

map(column_values)

Maps a dictionary to columns and values.

values(*values)

Appends values.

mysql

InsertQuery

Bases: InsertQuery

MySql InsertQuery that supports IGNORE.

SelectQuery

Bases: SelectQuery

Mysql SelectQuery that supports SQL_CALC_FOUND_ROWS.

insert_query
InsertQuery

Bases: InsertQuery

MySql InsertQuery that supports IGNORE.

select_query
SelectQuery

Bases: SelectQuery

Mysql SelectQuery that supports SQL_CALC_FOUND_ROWS.

postgres

InsertQuery

Bases: HasReturningMixin, InsertQuery

Postgres InsertQuery that supports RETURNING.

UpdateQuery

Bases: HasReturningMixin, UpdateQuery

Postgres UpdateQuery that supports RETURNING.

insert_query
InsertQuery

Bases: HasReturningMixin, InsertQuery

Postgres InsertQuery that supports RETURNING.

update_query
UpdateQuery

Bases: HasReturningMixin, UpdateQuery

Postgres UpdateQuery that supports RETURNING.

query

Query

The result of a compile.

params property

Returns all parameters of the SQL statement.

sql property

Returns the compiled SQL statement as a string.

select_query

SelectQuery

Bases: CanUnionMixin, HasFromMixin, HasOrderByMixin, HasWhereMixin, HasLimitMixin, HasOffsetMixin, AbstractQuery

Implements a SELECT query.

add_columns(*columns)

Add columns to the selection.

columns(*columns)

Set the columns to select.

distinct(state=True)

Add or remove DISTINCT.

full_join(table, criteria)

Add a FULL join.

group_by(*columns)

Add a GROUP BY clause.

having(criteria)

Add an HAVING clause.

inner_join(table, criteria)

Add an INNER join.

join(table, criteria, join_type='')

Add a join.

left_join(table, criteria)

Add a LEFT join.

right_join(table, criteria)

Add a RIGHT join.

with_(name=None, query=None, recursive=False)

Add a query as CTE.

When no name and query is passed, all CTE's for this query will be removed. When no query is passed, the CTE with the given name will be removed.

sql_server

DeleteQuery

Bases: DeleteQuery

Sql Server DeleteQuery to support LIMIT.

SelectQuery

Bases: SelectQuery

Sql Server SelectQuery to support offset and limit.

delete_query
DeleteQuery

Bases: DeleteQuery

Sql Server DeleteQuery to support LIMIT.

select_query
SelectQuery

Bases: SelectQuery

Sql Server SelectQuery to support offset and limit.

union_query

UnionQuery

Bases: CanUnionMixin, HasOrderByMixin, AbstractQuery

Implements a union query.

all(state=True)

Sets ALL.

update_query

UpdateQuery

Bases: HasWhereMixin, AbstractQuery

Implements an UPDATE query.

set(value_dict)

Sets the column and values with a dictionary.

table(table)

Sets the table.

query_factory

QueryFactory

Factory class for creating queries

delete(table)

Create a DELETE query

insert(table, column_values=None)

Create an INSERT query

select(*columns)

Create a SELECT query

select_distinct(*columns)

Create a SELECT DISTINCT query

update(table, value_set=None)

Create an UPDATE query