Skip to content

helpers.py

This file provides utility functions for text manipulation and standardized API response formatting. It ensures consistent data presentation and simplifies common tasks across the application, enhancing maintainability and developer experience.

Scope

  • Provides text formatting utilities for various purposes.

  • Generates URL-friendly slugs from input strings.

  • Truncates long text strings to a specified maximum length.

  • Standardizes error responses for API consistency.

  • Standardizes success responses for API consistency.

File diagram - "helpers.py" /app/utils/helpers.pyFile diagram - "helpers.py"  GlobalImportsdatetimerequote/app/utils/helpers.pyErrorResponseSuccessResponsegenerate_slug()truncate_text() generate_slugtexttext.lower()re.sub()text.strip()truncate_textlen()ErrorResponseerror()SuccessResponsesuccess()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
File diagram - "helpers.py" /app/utils/helpers.pyFile diagram - "helpers.py"  GlobalImportsdatetimerequote/app/utils/helpers.pyErrorResponseSuccessResponsegenerate_slug()truncate_text() generate_slugtexttext.lower()re.sub()text.strip()truncate_textlen()ErrorResponseerror()SuccessResponsesuccess()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Imports

  • datetime from datetime

    Provides date and time objects, used for potential timestamp generation or manipulation, ensuring accurate temporal data handling within various application contexts.

  • re

    Offers regular expression operations, crucial for pattern matching and string replacement in text processing functions like generate_slug, ensuring clean and valid output.

  • quote from urllib.parse

    Encodes URL components, ensuring special characters are correctly handled for safe inclusion in web addresses or paths, preventing malformed URLs and security issues.

Functions

generate_slug

public

This function transforms an input string into a URL-friendly slug by converting it to lowercase, replacing spaces with hyphens, and removing special characters. It ensures a clean, consistent format suitable for web addresses, identifiers, or file names across the application.
=== " "

Activity Diagram - "generate_slug" /app/utils/helpers.pyActivity Diagram - "generate_slug"  Inputs: textConvert text to lowercaseReplace whitespace with hyphensRemove non-alphanumeric characters and non-hyphensReplace multiple hyphens with a single hyphenRemove leading and trailing hyphensreturn Processed slug   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "generate_slug" /app/utils/helpers.pyActivity Diagram - "generate_slug"  Inputs: textConvert text to lowercaseReplace whitespace with hyphensRemove non-alphanumeric characters and non-hyphensReplace multiple hyphens with a single hyphenRemove leading and trailing hyphensreturn Processed slug   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "generate_slug" /app/utils/helpers.pyMethod diagram - "generate_slug"  generate_slugtexttext.lower()re.sub()text.strip()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "generate_slug" /app/utils/helpers.pyMethod diagram - "generate_slug"  generate_slugtexttext.lower()re.sub()text.strip()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "generate_slug" Sequence Diagram - "generate_slug"  generate_slugrerereCallergenerate_slugreCallerCallergenerate_sluggenerate_slugreregenerate_slugrerereFunction Callgenerate_slug(text)ProcessingConvert text to lowercasetext = text.lower()sub(r'\s+', '-', text)text_with_hyphensReplaces whitespace with hyphenssub(r'[^\w\-]', '', text)alphanumeric_textRemoves non-alphanumeric, non-hyphen characterssub(r'-+', '-', text)single_hyphen_textReplaces multiple hyphens with single hyphenStrip leading/trailing hyphenstext = text.strip('-')Function Returnslug/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "generate_slug" Sequence Diagram - "generate_slug"  generate_slugrerereCallergenerate_slugreCallerCallergenerate_sluggenerate_slugreregenerate_slugrerereFunction Callgenerate_slug(text)ProcessingConvert text to lowercasetext = text.lower()sub(r'\s+', '-', text)text_with_hyphensReplaces whitespace with hyphenssub(r'[^\w\-]', '', text)alphanumeric_textRemoves non-alphanumeric, non-hyphen characterssub(r'-+', '-', text)single_hyphen_textReplaces multiple hyphens with single hyphenStrip leading/trailing hyphenstext = text.strip('-')Function Returnslug/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def generate_slug(text: str) -> str:

Input Parameters

  • text (str)

    The input string to be converted into a slug. This text typically represents a title or name that needs to be made URL-safe. It should be a non-empty string for effective slug generation.

Output / Return Values

  • slug (str)

    The generated URL-friendly slug string. This output is a lowercase, hyphen-separated version of the input, free from special characters. It is suitable for use in URLs or unique identifiers.

Logic / Execution Flow

  • Convert the input text to its lowercase representation using text.lower().
  • Replace all occurrences of one or more whitespace characters (\s+) in the text with a single hyphen (-) using re.sub().
  • Remove any characters from text that are not word characters (\w) or hyphens (-) using re.sub().
  • Replace sequences of one or more hyphens (-+) in the text with a single hyphen (-) using re.sub().
  • Remove any leading or trailing hyphens from the text using text.strip('-').
  • Return the final processed text string, which is the generated slug.

Usage Tips

  • Always use this generate_slug function when creating URL paths or unique identifiers from user-provided titles. This ensures consistency and avoids issues with special characters in web contexts.

  • Consider applying this slug generation early in your data processing pipeline, especially before saving content to a database. This standardizes identifiers and simplifies retrieval and routing later.

Additional Notes

  • The current implementation uses a basic regex for character removal, which might be too aggressive for some international characters. For broader language support, consider a more sophisticated Unicode-aware slugification library.

  • While effective for basic slug generation, this function does not guarantee uniqueness. If slugs must be unique, implement additional logic to check for existing slugs and append a differentiator like a number.

truncate_text

public

Truncates a given string `text` to a specified `max_length`, appending a `suffix` if truncation occurs. This function is useful for displaying shortened content previews or ensuring text fits within UI constraints effectively.
=== " "

Activity Diagram - "truncate_text" /app/utils/helpers.pyActivity Diagram - "truncate_text"  Inputs: text, max_length, suffixLength of text <= max_length?yesnoreturn Original textCalculate length of suffixDetermine truncation point (max_length - suffix length)Slice text from start to truncation pointConcatenate sliced text with suffixreturn Truncated text with suffix   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "truncate_text" /app/utils/helpers.pyActivity Diagram - "truncate_text"  Inputs: text, max_length, suffixLength of text <= max_length?yesnoreturn Original textCalculate length of suffixDetermine truncation point (max_length - suffix length)Slice text from start to truncation pointConcatenate sliced text with suffixreturn Truncated text with suffix   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "truncate_text" /app/utils/helpers.pyMethod diagram - "truncate_text"  truncate_textlen()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "truncate_text" /app/utils/helpers.pyMethod diagram - "truncate_text"  truncate_textlen()   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "truncate_text" Sequence Diagram - "truncate_text"  truncate_textCallertruncate_textCallerCallertruncate_texttruncate_texttruncate_textFunction Calltruncate_text(text, max_length, suffix)Check LengthGet length of text (len(text))Text is short enough, no truncation neededalt[len(text) <= max_length]Return original text[len(text) > max_length]Get length of suffix (len(suffix))Calculate slice end index (max_length - len(suffix))Slice text (text[:slice_end_index])Concatenate suffix with sliced textReturn truncated text/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "truncate_text" Sequence Diagram - "truncate_text"  truncate_textCallertruncate_textCallerCallertruncate_texttruncate_texttruncate_textFunction Calltruncate_text(text, max_length, suffix)Check LengthGet length of text (len(text))Text is short enough, no truncation neededalt[len(text) <= max_length]Return original text[len(text) > max_length]Get length of suffix (len(suffix))Calculate slice end index (max_length - len(suffix))Slice text (text[:slice_end_index])Concatenate suffix with sliced textReturn truncated text/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def truncate_text(text: str, max_length: int = 150, suffix: str = "...") -> str:

Input Parameters

  • text (str)

    The original string to be potentially truncated. This input represents the full content that might exceed the desired length, requiring shortening for display or storage purposes.

  • max_length (int)

    The maximum desired length for the output string, including the suffix. This parameter defines the upper bound for the returned string's character count, ensuring concise presentation.

  • suffix (str)

    The string appended to the truncated text, indicating that content has been shortened. This suffix helps users understand that the displayed text is not the complete original message.

Output / Return Values

  • truncated_string (str)

    The potentially truncated string, with the suffix appended if truncation occurred. This output provides a concise version of the original text, suitable for display within limited space.

Logic / Execution Flow

  • Check if the length of the input text is less than or equal to max_length:
    • If len(text) is less than or equal to max_length:
      • Return the original text as no truncation is necessary.
    • If len(text) is greater than max_length:
      • Calculate the truncation point by subtracting the suffix length from max_length.
      • Truncate text to this calculated length.
      • Concatenate the truncated text with the suffix.
      • Return the newly formed truncated string.

Usage Tips

  • Ensure max_length is always greater than or equal to the suffix length to prevent negative slicing errors. This guarantees the suffix always fits within the specified maximum length.

  • Consider using this function for UI elements like card descriptions or list item summaries. It helps maintain consistent layout and readability without overflowing content boundaries effectively.

Additional Notes

  • This function performs simple character-based truncation, which might cut words in half. For more sophisticated truncation that preserves whole words, consider using a dedicated text processing library.

  • The max_length parameter includes the length of the suffix. Adjust max_length accordingly if you need a specific number of characters before the ellipsis for precise control.

Classes

SuccessResponse

Provides a standardized structure for API success responses, encapsulating data and messages. Facilitates consistent communication of successful operations across the system, enhancing client-side parsing and error handling logic for robust integration.

Class diagram - "SuccessResponse" /app/utils/helpers.pyClass diagram - "SuccessResponse"  SuccessResponsesuccess()success   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Class diagram - "SuccessResponse" /app/utils/helpers.pyClass diagram - "SuccessResponse"  SuccessResponsesuccess()success   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Methods

success

public

This method constructs a standardized success response dictionary for API operations. It encapsulates a boolean success flag, a descriptive message, and optional data payload. This consistent structure aids client-side parsing and error handling across various application endpoints.
=== " "

Activity Diagram - "success" /app/utils/helpers.pyActivity Diagram - "success"  Inputs: data, messageConstruct dictionary with success=True, provided message, andprovided datareturn Success response dictionary   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "success" /app/utils/helpers.pyActivity Diagram - "success"  Inputs: data, messageConstruct dictionary with success=True, provided message, andprovided datareturn Success response dictionary   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "success" /app/utils/helpers.pyMethod diagram - "success"  success   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "success" /app/utils/helpers.pyMethod diagram - "success"  success   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "success" Sequence Diagram - "success"  successCallersuccessCallerCallersuccesssuccesssuccessFunction Callsuccess(data, message)Internal ProcessingConstruct dictionary with "success": TrueSet "message" field from inputSet "data" field from inputFunction ReturnReturn {"success": True, "message": message, "data": data}/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "success" Sequence Diagram - "success"  successCallersuccessCallerCallersuccesssuccesssuccessFunction Callsuccess(data, message)Internal ProcessingConstruct dictionary with "success": TrueSet "message" field from inputSet "data" field from inputFunction ReturnReturn {"success": True, "message": message, "data": data}/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def success(data=None, message: str = "Success"):

Input Parameters

  • data (Any)

    This optional parameter represents any arbitrary data payload to include in the success response. It can be a dictionary, list, or any serializable object. Useful for returning results of successful operations.

  • message (str)

    This string parameter provides a human-readable message indicating the success of the operation. It defaults to "Success" but can be customized for specific contexts. Crucial for user feedback.

Output / Return Values

  • response_object (dict)

    This method returns a dictionary containing success, message, and data keys. It provides a consistent structure for successful API responses. Clients can reliably parse this object to determine operation outcomes.

Logic / Execution Flow

  • Construct a dictionary containing a success status set to True, the provided message, and the data payload.
  • Return the constructed dictionary as the method's output.

Usage Tips

  • Utilize this success() method consistently across all API endpoints to maintain uniform response formatting. This standardisation simplifies client-side integration, reduces parsing errors, and enhances overall API usability and developer experience.

  • Always provide meaningful message strings when using this method, especially for user-facing operations. Clear messages improve debugging, aid user understanding, and contribute to a better overall application experience.

Additional Notes

  • While data is flexible, ensure the content is JSON-serializable for API responses. Complex objects might require custom serialization logic before being passed to this method for consistent client consumption.

  • This static method is stateless and purely functional, making it highly reusable across different parts of the application. Its simplicity ensures predictable behavior and minimal overhead when generating success responses.

ErrorResponse

Provides a utility for generating standardised error response dictionaries across the application. This class centralises error message formatting, status code assignment, and detailed information for consistent API error handling and client communication.

Class diagram - "ErrorResponse" /app/utils/helpers.pyClass diagram - "ErrorResponse"  ErrorResponseerror()error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Class diagram - "ErrorResponse" /app/utils/helpers.pyClass diagram - "ErrorResponse"  ErrorResponseerror()error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Methods

error

public

Constructs a standardised error response dictionary for API endpoints or internal error handling. This utility method provides consistent formatting for error messages, status codes, and optional detailed explanations across the application.
=== " "

Activity Diagram - "error" /app/utils/helpers.pyActivity Diagram - "error"  Inputs: message, status_code, detailConstruct error dictionary with success=False, provided message,detail, and status_codereturn Constructed error dictionary   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Activity Diagram - "error" /app/utils/helpers.pyActivity Diagram - "error"  Inputs: message, status_code, detailConstruct error dictionary with success=False, provided message,detail, and status_codereturn Constructed error dictionary   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Method diagram - "error" /app/utils/helpers.pyMethod diagram - "error"  error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Method diagram - "error" /app/utils/helpers.pyMethod diagram - "error"  error   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Sequence Diagram - "error" Sequence Diagram - "error"  errorCallererrorCallerCallererrorerrorerrorFunction Callerror(message, status_code, detail)Internal ProcessingConstruct dictionarySets "success" to False and "status_code" to 400 if not providedFunction ReturnReturn error dictionary/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Sequence Diagram - "error" Sequence Diagram - "error"  errorCallererrorCallerCallererrorerrorerrorFunction Callerror(message, status_code, detail)Internal ProcessingConstruct dictionarySets "success" to False and "status_code" to 400 if not providedFunction ReturnReturn error dictionary/app/utils/helpers.py   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Syntax

def error(message: str, status_code: int = 400, detail: str = None):

Input Parameters

  • message (str)

    A concise, human-readable error message explaining the problem. This message is crucial for user feedback and logging, providing immediate context about the encountered issue or failure condition.

  • status_code (int)

    The HTTP status code associated with the error, defaulting to 400 (Bad Request). This code indicates the nature of the error to clients, guiding appropriate handling and response strategies effectively.

  • detail (str)

    An optional, more detailed explanation of the error, providing additional context. This can include specific validation failures or internal system information, aiding debugging and comprehensive problem resolution.

Output / Return Values

  • error_response_dictionary (dict)

    A dictionary containing success: False, the message, detail, and status_code. This structured output ensures consistent error reporting, facilitating client-side parsing and uniform error display across various application interfaces.

Logic / Execution Flow

  • Construct a dictionary with the following key-value pairs:
    • "success": Set to False to indicate an unsuccessful operation.
    • "message": Set to the value of the message input parameter.
    • "detail": Set to the value of the detail input parameter.
    • "status_code": Set to the value of the status_code input parameter.
  • Return the newly constructed error response dictionary.

Usage Tips

  • Utilise this error() method consistently across all API endpoints to ensure uniform error response structures. This standardisation greatly simplifies client-side error handling logic and improves overall API usability for developers.

  • Always provide a clear, user-friendly message and a more technical detail when appropriate. This distinction helps both end-users understand issues and developers debug problems efficiently, enhancing communication.

Additional Notes

  • This method is a static utility, meaning it does not depend on instance state and can be called directly on the class. It serves purely as a factory for creating error dictionaries, not for error handling itself.

  • While status_code defaults to 400, ensure you select the most appropriate HTTP status code for each specific error scenario. Correct status codes are vital for proper RESTful API design and client interpretation.

FAQs

Why are ErrorResponse and SuccessResponse implemented as classes with static methods?

This design provides a consistent, centralized way to construct standardized API responses, promoting uniformity and reducing boilerplate code across various endpoints, enhancing maintainability and clarity.

Why is generate_slug implemented with multiple re.sub calls?

The sequential re.sub calls ensure a robust slug generation process, handling spaces, non-alphanumeric characters, and multiple hyphens effectively for clean, URL-friendly identifiers, improving SEO.

Why is truncate_text designed to append a suffix?

Appending a suffix like "..." clearly indicates to the user that the displayed text is a shortened version of the original content, improving user experience and preventing information loss perception.

Insights

Metric Score Level
Complexity 0.20 Simple
Security 0.80 Secure
Performance 0.90 Optimised