Utils
This package contains utilities which facilitate specific tasks and can be re-used and imported from different locations.
Account Activation Token Generator
This module contains helpers for the account activation process
(also see AccountActivationView
).
- class integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator[source]
Bases:
PasswordResetTokenGenerator
This token generator is identical to the default password reset token generator of
django.contrib.auth
with the exception of the used HMAC salt. This means password reset tokens are no longer accepted for the account activation and vice versa.- key_salt = 'integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator'[source]
The key salt which is passed to the HMAC function
- integreat_cms.cms.utils.account_activation_token_generator.account_activation_token_generator = <integreat_cms.cms.utils.account_activation_token_generator.AccountActivationTokenGenerator object>[source]
The token generator for the account activation process (an instance of
AccountActivationTokenGenerator
)
Content Edit Lock
This file contains a mechanism to lock a content editor for other people while a person is using it.
- integreat_cms.cms.utils.content_edit_lock.get_cache_key(id_: int | str, type_: str) str [source]
This function returns the key that is used to lock a content object in the cache. It should not be used outside of this module.
- integreat_cms.cms.utils.content_edit_lock.get_locking_user(id_: int | str | None, type_: str) User | None [source]
This function returns the user that locks a specific object
- integreat_cms.cms.utils.content_edit_lock.lock_content(id_: int | None, type_: str, user: User) bool [source]
This function tries to lock a content object for a user. If it is already locked by someone else, nothing will happen. If it is already locked by the same user, the timeout gets reset.
Email Utils
- integreat_cms.cms.utils.email_utils.send_mail(subject: str, email_template_name: str, html_email_template_name: str, context: dict[str, Any], recipient: str) None [source]
Sends welcome email to user with new account.
Making use of
EmailMultiAlternatives
andMIMEImage
to send a multipart email with plain text and html version and also attach the branding logo.- Parameters:
- Return type:
None
File Utils
This module contains helpers for file handling.
- integreat_cms.cms.utils.file_utils.create_zip_archive(source_file_paths: list[str], zip_file_path: str) None [source]
Create zip file from list of source files
- integreat_cms.cms.utils.file_utils.extract_zip_archive(zip_file_path: str, target_directory: str, allowed_file_extensions: Any | None = None) tuple[list[str], list] [source]
Extract zip file and return file paths of content. Returns a tuple of extracted and invalid files:
extracted_files, invalid_files = extract_zip_archive(zip_file_path, target_directory, allowed_file_extensions)
If want to extract all files regardless of their extension, discard the second return value:
extracted_files, _ = extract_zip_archive(zip_file_path, target_directory)
- Parameters:
- Returns:
a tuple of two lists of the valid and invalid filenames
- Return type:
Internal Link Checker
- integreat_cms.cms.utils.internal_link_checker.check_event_or_location(content_type: str, manager: RelatedManager, url: Url, path_components: list[str], region: Region, language: Language) bool [source]
Check whether the event or location with that URL exists in the given region and language. Fallback translations are also checked when they are enabled in the specific region.
- Parameters:
- Returns:
The validity status of the URL
- Return type:
- integreat_cms.cms.utils.internal_link_checker.check_imprint(url: Url, path_components: list[str], region: Region, language: Language) bool [source]
Check whether the imprint exists in the given region and language
- integreat_cms.cms.utils.internal_link_checker.check_internal(url: Url) bool | None [source]
- Parameters:
url (Url) – The internal URL to check
- Returns:
The status of the URL
- Return type:
bool | None
- integreat_cms.cms.utils.internal_link_checker.check_news_link(url: Url, path_components: list[str], region: Region, language: Language) bool | None [source]
Check whether the news exists in the given region
- integreat_cms.cms.utils.internal_link_checker.check_object_link(content_type: str, manager: RelatedManager, slug: str, url: Url, region: Region, language: Language) bool [source]
Check whether the given content objects are valid
- integreat_cms.cms.utils.internal_link_checker.check_offer_link(url: Url, path_components: list[str], region: Region) bool [source]
Check whether the offer exists in the given region
- integreat_cms.cms.utils.internal_link_checker.check_translation_link(content_object: Event | Page | POI, url: Url, language: Language) bool [source]
Check whether the link of the given content object is valid
Internal Link Utils
This file contains utility functions for recognizing and modifying internal links
- integreat_cms.cms.utils.internal_link_utils.get_public_translation_for_link(url: str, current_language_slug: str | None = None) AbstractContentTranslation | None [source]
This function gets the public content translation object corresponding to the path of an internal url. If the url does not refer to any object, this function will return None. This function handles webapp links and short urls. If the language of the url is the same as current_language_slug, this function will return None.
- Parameters:
- Returns:
The latest corresponding content translation
- Return type:
AbstractContentTranslation | None
- integreat_cms.cms.utils.internal_link_utils.get_public_translation_for_short_link(path: str) AbstractContentTranslation | None [source]
Calculates the content object that corresponds to the short url path and returns its latest public translation.
- Parameters:
path (str) – The url path, for example given the url ‘http://localhost:8000/s/p/124/’ it would be ‘/s/p/124/’
- Returns:
The latest corresponding content translation
- Return type:
AbstractContentTranslation | None
- integreat_cms.cms.utils.internal_link_utils.get_public_translation_for_webapp_link(path: str, current_language_slug: str | None = None) AbstractContentTranslation | None [source]
Calculates the content object that corresponds to the webapp url path and returns its latest public translation.
- Parameters:
path (str) – The url path, for example given the url ‘https://integreat.app/augsburg/de/willkommen/’ it would be ‘/augsburg/de/willkommen/’
current_language_slug (str | None) – A language slug that will cause the function to return early if contained in the url
- Returns:
The latest corresponding content translation
- Return type:
AbstractContentTranslation | None
- integreat_cms.cms.utils.internal_link_utils.update_link_language(current_link: str, link_text: str, target_language_slug: str) tuple[str, str] | None [source]
Fixes the link, so that it points to the correct language. Returns a tuple of the translated url and (potentially) translated title. For example, with current_link = ‘https://integreat.app/augsburg/de/willkommen/’ and language_slug = ‘en’ a possible return value could be (’https://integreat.app/augsburg/en/welcome/, ‘Welcome’). Note that the resulting link might refer to a fallback language and not the actual target language.
Linkcheck Utils
- integreat_cms.cms.utils.linkcheck_utils.filter_urls(region_slug: str | None = None, url_filter: str | None = None, prefetch_content_objects: bool = True) tuple[list[Url], dict[str, int]] [source]
Filter all urls of one region by the given category
- Parameters:
region_slug (str | None) – The slug of the current region
url_filter (str | None) – Which urls should be returned (one of
valid
,invalid
,ignored
,unchecked
). If parameter is not in these choices or omitted, all urls are returned by default.prefetch_content_objects (bool) – Whether or not content objects should be prefetched
- Returns:
A tuple of the requested urls and a dict containing the counters of all remaining urls
- Return type:
- integreat_cms.cms.utils.linkcheck_utils.fix_content_link_encoding(content: str) str [source]
Fix the encoding of punycode domains in an html content string
- integreat_cms.cms.utils.linkcheck_utils.fix_domain_encoding(url: Match[str]) str [source]
Fix the encoding of punycode domains
- integreat_cms.cms.utils.linkcheck_utils.get_region_links(region: Region) Query [source]
Returns the links of translations of the given region :param region: The region :return: A query containing the relevant links
- Parameters:
region (Region) –
- Return type:
Query
- integreat_cms.cms.utils.linkcheck_utils.get_url_count(region_slug: str | None = None) dict[str, int] [source]
Count all urls by status. The content objects are not prefetched because they are not needed for the counter.
- integreat_cms.cms.utils.linkcheck_utils.get_urls(region_slug: str | None = None, url_ids: Any | None = None, prefetch_content_objects: bool = True) list[Url] [source]
Collect all the urls which appear in the latest versions of the contents of the region, filtered by ID or region if given.
- integreat_cms.cms.utils.linkcheck_utils.replace_link_helper(old_url: str, new_url: str, link: str) str [source]
A small helper function which can be passed to
lxml.html.HtmlMixin.rewrite_links()
- integreat_cms.cms.utils.linkcheck_utils.replace_links(search: str, replace: str, *, region: Region | None = None, user: User | None = None, commit: bool = True, link_types: list[str] | None = None) None [source]
Perform search & replace in the content links
- Parameters:
search (str) – The (partial) URL to search
replace (str) – The (partial) URL to replace
region (Region | None) – Optionally limit the replacement to one region (
None
means a global replacement)user (User | None) – The creator of the replaced translations
commit (bool) – Whether changes should be written to the database
link_types (list[str] | None) – Which kind of links should be replaced
- Return type:
None
- integreat_cms.cms.utils.linkcheck_utils.save_new_version(translation: AbstractContentTranslation, new_translation: AbstractContentTranslation, user: Any | None) None [source]
Save a new translation version
- Parameters:
translation (AbstractContentTranslation) – The old translation
new_translation (AbstractContentTranslation) – The new translation
user (Any | None) – The creator of the new version
- Return type:
None
Media Utils
Utility functions for the media management. Most of the functions are used to transform media data to other data types.
- integreat_cms.cms.utils.media_utils.generate_thumbnail(original_image: InMemoryUploadedFile, size: int = 300, crop: bool = False) InMemoryUploadedFile | None [source]
Creates a thumbnail for a given media_file.
- Parameters:
original_image (InMemoryUploadedFile) – Original image for the thumbnail
size (int) – Desired size of the thumbnail (maximum for height and with), defaults to
MEDIA_THUMBNAIL_SIZE
crop (bool) – Whether the thumbnail should be cropped (resulting in a square regardless of the initial aspect ratio), defaults to
MEDIA_THUMBNAIL_CROP
- Returns:
The created thumbnail in memory
- Return type:
InMemoryUploadedFile | None
MFA Utils
This module contains helpers for multi-factor-authentication tasks.
- integreat_cms.cms.utils.mfa_utils.generate_challenge(challenge_len: int) str [source]
This function generates a random challenge of the given length. It consists of ascii letters and digits.
Example usage:
GetMfaChallengeView
- integreat_cms.cms.utils.mfa_utils.get_mfa_user(request: HttpRequest) User | None [source]
Get the user from the session if it exists. This method can be used for the passwordless login, as well as the usual login mode.
- Parameters:
request (HttpRequest) – The current request
- Returns:
The user
- Return type:
User | None
PDF Utils
- integreat_cms.cms.utils.pdf_utils.generate_pdf(region: Region, language_slug: str, pages: PageQuerySet) HttpResponseRedirect [source]
Function for handling a pdf export request for pages. The pages were either selected by cms user or by API request (see
pdf_export()
) For more information on xhtml2pdf, see Welcome to xhtml2pdf’s documentation!- Parameters:
region (Region) – region which requested the pdf document
language_slug (str) – bcp47 slug of the current language
pages (PageQuerySet) – at least on page to render as PDF document
- Returns:
Redirection to PDF document
- Return type:
HttpResponseRedirect
Slug Utils
This module contains helpers regarding unique string identifiers without special characters (“slugs”).
- integreat_cms.cms.utils.slug_utils.generate_unique_slug(**kwargs: Unpack[SlugKwargs]) str [source]
This function can be used in
forms
to clean slug fields. It will make sure the slug field contains a unique identifier per region and language. It can also be used for region slugs (foreign_model
isNone
in this case). If the slug field is empty, it creates a fallback value from either thetitle
or thename
field. In case the slug exists already, it appends a counter which is increased until the slug is unique.Example usages:
- Parameters:
**kwargs (Unpack[SlugKwargs]) – The supplied keyword arguments
- Raises:
ValidationError – When no slug is given and there is also no field which can be used as fallback (either
title
orname
).- Returns:
An unique slug identifier
- Return type:
- integreat_cms.cms.utils.slug_utils.generate_unique_slug_helper(form_object: ModelForm, foreign_model: ForeignModelType) str [source]
This function acts like an interface and extracts all parameters of the form_object before actually generating the unique slug, so that unique slug generation can be performed without any cleaned form data after a form submission.
- Parameters:
form_object (ModelForm) – The form which contains the slug field
foreign_model (ForeignModelType) – If the form instance has a foreign key to another model (e.g. because it is a translation of a content-object), this parameter contains the model of the foreign related object.
- Raises:
ValidationError – When no slug is given and there is also no field which can be used as fallback (either
title
orname
).- Returns:
An unique slug identifier
- Return type:
Stringify List
- integreat_cms.cms.utils.stringify_list.iter_to_string(iterable: Iterable, *, quotation_char: str = '"', max_items: int = 5) str [source]
This is a helper function that turns a list into a string using different delimiters.
- Parameters:
- Returns:
Returns string with the single items separated by comma expect the last item which is separated by ‘and’.
- Return type:
Text Utils
This module contains helpers for strings.
- integreat_cms.cms.utils.text_utils.lowfirst(string: Promise) str [source]
Make the first letter of a string lowercase (counterpart of
capfirst()
, see alsocapfirst
).- Parameters:
string (Promise) – The input text
- Returns:
The lowercase text
- Return type:
Totp Utils
This module contains helper functions that are used within the TOTP registration and authentication.
- integreat_cms.cms.utils.totp_utils.check_totp_code(given_totp_code: str, key: str) bool [source]
Helper method to check the given code with the initial key
Translation Utils
This module contains helpers for the gettext translation process of UI languages.
- integreat_cms.cms.utils.translation_utils.gettext_many_lazy(*strings: Any) Promise [source]
This function is a wrapper for
django.utils.text.format_lazy()
for the special case that the given strings should be concatenated with a space in between. This is useful for splitting lazy translated strings by sentences which improves the translation memory.- Parameters:
*strings (Any) – A list of lazy translated strings which should be concatenated
- Returns:
A lazy formatted string
- Return type:
Promise
- integreat_cms.cms.utils.translation_utils.translate_link(message: Promise | str, attributes: dict[str, str]) SafeString [source]
Translate a link with keeping the HTML tags and still escaping all unknown parts of the message
- Parameters:
- Returns:
A correctly escaped formatted string with the translated message and the HTML link
- Return type:
SafeString
User Utils
- integreat_cms.cms.utils.user_utils.search_users(region: Region | None, query: str) QuerySet[User] [source]
Searches for all users that match the given query. If region is None, all users are searched. :param region: The current region :param query: The query string used for filtering the regions :return: A query for all matching objects
Welcome Mail Utils
- integreat_cms.cms.utils.welcome_mail_utils.send_welcome_mail(request: HttpRequest, user: User, activation: bool) None [source]
Sends welcome email to user with new account.
Making use of
EmailMultiAlternatives
andMIMEImage
to send a multipart email with plain text and html version and also attach the integreat logo.