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.
Imports
-
datetime from datetimeProvides date and time objects, used for potential timestamp generation or manipulation, ensuring accurate temporal data handling within various application contexts.
-
reOffers 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.parseEncodes 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.
def generate_slug(text: str) -> str:
text(str)The input string to be converted into a slug. This
texttypically represents a title or name that needs to be made URL-safe. It should be a non-empty string for effective slug generation.
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.
- Convert the input
textto its lowercase representation usingtext.lower(). - Replace all occurrences of one or more whitespace characters (
\s+) in thetextwith a single hyphen (-) usingre.sub(). - Remove any characters from
textthat are not word characters (\w) or hyphens (-) usingre.sub(). - Replace sequences of one or more hyphens (
-+) in thetextwith a single hyphen (-) usingre.sub(). - Remove any leading or trailing hyphens from the
textusingtext.strip('-'). - Return the final processed
textstring, which is the generated slug.
Usage Tips
-
Always use this
generate_slugfunction 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.
def truncate_text(text: str, max_length: int = 150, suffix: str = "...") -> str:
-
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
suffixhelps users understand that the displayed text is not the complete original message.
truncated_string(str)The potentially truncated string, with the
suffixappended if truncation occurred. This output provides a concise version of the originaltext, suitable for display within limited space.
- Check if the length of the input
textis less than or equal tomax_length:- If
len(text)is less than or equal tomax_length:- Return the original
textas no truncation is necessary.
- Return the original
- If
len(text)is greater thanmax_length:- Calculate the truncation point by subtracting the
suffixlength frommax_length. - Truncate
textto this calculated length. - Concatenate the truncated
textwith thesuffix. - Return the newly formed truncated string.
- Calculate the truncation point by subtracting the
- If
Usage Tips
-
Ensure
max_lengthis always greater than or equal to thesuffixlength to prevent negative slicing errors. This guarantees thesuffixalways 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_lengthparameter includes the length of thesuffix. Adjustmax_lengthaccordingly 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.
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.
def success(data=None, message: str = "Success"):
-
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.
response_object(dict)This method returns a dictionary containing
success,message, anddatakeys. It provides a consistent structure for successful API responses. Clients can reliably parse this object to determine operation outcomes.
- Construct a dictionary containing a
successstatus set toTrue, the providedmessage, and thedatapayload. - 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
messagestrings 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
datais 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.
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.
def error(message: str, status_code: int = 400, detail: str = None):
-
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.
error_response_dictionary(dict)A dictionary containing
success: False, themessage,detail, andstatus_code. This structured output ensures consistent error reporting, facilitating client-side parsing and uniform error display across various application interfaces.
- Construct a dictionary with the following key-value pairs:
"success": Set toFalseto indicate an unsuccessful operation."message": Set to the value of themessageinput parameter."detail": Set to the value of thedetailinput parameter."status_code": Set to the value of thestatus_codeinput 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
messageand a more technicaldetailwhen 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_codedefaults to400, 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.subcalls 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 |