### MarkupSafe Installation Source: https://context7.com/pallets/markupsafe/llms.txt Instructions on how to install the MarkupSafe library using pip. ```APIDOC ## Installation Install MarkupSafe via pip. ```bash pip install -U MarkupSafe ``` ``` -------------------------------- ### Install MarkupSafe using pip Source: https://github.com/pallets/markupsafe/blob/main/docs/index.md Provides the command to install or update the MarkupSafe library using pip, the standard package installer for Python. ```text pip install -U MarkupSafe ``` -------------------------------- ### Implement custom HTML formatting for objects Source: https://github.com/pallets/markupsafe/blob/main/docs/formatting.md This example demonstrates how to implement the __html_format__ and __html__ methods within a class to define custom rendering logic for MarkupSafe. It shows how to handle specific format specifiers like 'link' and ensure proper escaping of user-provided content. ```python class User(object): def __init__(self, id, name): self.id = id self.name = name def __html_format__(self, format_spec): if format_spec == "link": return Markup( '{}' ).format(self.id, self.__html__()) elif format_spec: raise ValueError("Invalid format spec") return self.__html__() def __html__(self): return Markup( '{0}' ).format(self.name) ``` -------------------------------- ### Define custom HTML representation with __html__ Source: https://github.com/pallets/markupsafe/blob/main/docs/html.md This example demonstrates how to create a class that implements the __html__ method to return a safe HTML string. It shows both the class definition and the resulting behavior when passed to the Markup constructor. ```python class Image: def __init__(self, url): self.url = url def __html__(self): return f'' ``` ```pycon >>> img = Image("/static/logo.png") >>> Markup(img) Markup('') ``` -------------------------------- ### Securely escaping user data within __html__ Source: https://github.com/pallets/markupsafe/blob/main/docs/html.md This example illustrates how to safely include user-provided data within an __html__ method by using the escape function. This ensures that while the tag structure is trusted, the dynamic content remains sanitized. ```python class User: def __init__(self, id, name): self.id = id self.name = name def __html__(self): return f'{escape(self.name)}' ``` ```pycon >>> user = User(3, "") # wrap in Markup to mark text "safe" and prevent escaping Markup("Hello") escape(Markup("Hello")) # Markup is a str subclass # methods and operators escape their arguments template = Markup("Hello {name}") template.format(name='"World"') ``` -------------------------------- ### Perform printf-style formatting with Markup Source: https://github.com/pallets/markupsafe/blob/main/docs/formatting.md Shows how to use standard Python printf-style formatting with Markup strings. The content is automatically escaped while maintaining the structure of the format string. ```pycon >>> user = User(3, "") print(untrusted) safe_text = Markup("Hello ") result = safe_text + "" print(result) html = Markup("

hello world

") print(html.upper()) ``` -------------------------------- ### Convert HTML entities with unescape() Source: https://context7.com/pallets/markupsafe/llms.txt Demonstrates how to revert HTML entities back to their original character representations using the unescape method. ```python from markupsafe import Markup escaped = Markup("Main » <em>About</em>") plain_text = escaped.unescape() print(plain_text) entities = Markup("& < > " ' ©") print(entities.unescape()) ``` -------------------------------- ### Markup.join() Method Source: https://context7.com/pallets/markupsafe/llms.txt Demonstrates how to use the Markup.join() method to safely concatenate an iterable of strings with a Markup separator, ensuring proper HTML escaping. ```APIDOC ## Markup.join() Method The `join()` method joins an iterable of strings with the `Markup` separator, escaping each element. This is useful for safely building lists of HTML elements from potentially unsafe strings. ### Method `Markup.join(iterable)` ### Parameters - **iterable** (iterable) - An iterable of strings to join. ### Request Example ```python from markupsafe import Markup # Join list items with separator, escaping each item items = ["Home", "About ", "Contact & Info"] nav = Markup(" | ").join(items) print(nav) # Output: Home | About <us> | Contact & Info # Build HTML lists safely list_items = ["") print(result) # Output:

Hello, <script>alert('xss')</script>!

# Printf-style formatting also escapes values user_name = "" safe_output = escape(user_input) print(safe_output) print(escape(42)) class SafeLink: def __html__(self): return 'Home' link = SafeLink() print(escape(link)) ``` -------------------------------- ### Markup String Methods Preserve Safety in Python Source: https://context7.com/pallets/markupsafe/llms.txt Explains how standard Python string methods, when called on `Markup` objects, return `Markup` instances, thus preserving the safety of the HTML. This includes methods like `split()`, `upper()`, `replace()`, and `strip()`, ensuring that operations on safe HTML strings remain safe. ```python from markupsafe import Markup html = Markup("

Hello, World!

") # split() returns list of Markup parts = html.split(",") print(parts) # Output: [Markup('

Hello'), Markup(' World!

')] print(type(parts[0])) # Output: # Case transformation print(html.upper()) # Output:

HELLO, WORLD!

print(html.lower()) # Output:

hello, world!

print(html.title()) # Output:

Hello, World!

# replace() escapes the replacement string template = Markup("
PLACEHOLDER
") result = template.replace("PLACEHOLDER", "") print(result) # Output:
<user input>
# strip methods work normally padded = Markup("

content

") print(padded.strip()) # Output:

content

# Slicing preserves Markup type print(html[3:10]) # Output: >Hello, print(type(html[3:10])) # Output: ``` -------------------------------- ### Safely Join Strings with Markup.join() in Python Source: https://context7.com/pallets/markupsafe/llms.txt Illustrates the use of the `Markup.join()` method in Python to concatenate an iterable of strings using a `Markup` separator. This method ensures that each element is safely escaped, preventing XSS vulnerabilities when building HTML structures like navigation menus or lists. ```python from markupsafe import Markup # Join list items with separator, escaping each item items = ["Home", "About ", "Contact & Info"] nav = Markup(" | ").join(items) print(nav) # Output: Home | About <us> | Contact & Info # Build HTML lists safely list_items = ["") print(untrusted) # Output: <script>bad</script> # String concatenation automatically escapes the added text safe_text = Markup("Hello ") result = safe_text + "" print(result) # Output: Hello <script>alert('xss')</script> # Multiplication works as expected repeated = Markup("
") * 3 print(repeated) # Output:


# All str methods return Markup and preserve safety html = Markup("

hello world

") print(html.upper()) # Output:

HELLO WORLD

print(html.replace("world", "universe")) # Output:

hello universe

``` ``` -------------------------------- ### Handle optional values with escape_silent Source: https://github.com/pallets/markupsafe/blob/main/docs/escaping.md The escape_silent function behaves like escape but treats None as an empty string instead of the literal string 'None'. ```python from markupsafe import escape_silent print(escape_silent(None)) ``` -------------------------------- ### markupsafe.escape_silent Source: https://github.com/pallets/markupsafe/blob/main/docs/escaping.md Similar to `escape()`, but treats `None` input as an empty string, preventing 'None' from being rendered in HTML. ```APIDOC ## markupsafe.escape_silent(s,) ### Description Like [`escape()`](#markupsafe.escape) but treats `None` as the empty string. Useful with optional values, as otherwise you get the string `'None'` when the value is `None`. ### Parameters * **s** (Any | None) - An object to be converted to a string and escaped, or None. ### Returns A [`Markup`](#markupsafe.Markup) string with the escaped text, or an empty Markup string if input is None. ### Return type Markup ``` -------------------------------- ### Unescape and strip tags from Markup objects Source: https://github.com/pallets/markupsafe/blob/main/docs/escaping.md Markup objects provide methods to revert HTML entities to characters or remove HTML tags entirely while normalizing whitespace. ```python from markupsafe import Markup m = Markup("Main » About") print(m.unescape()) print(m.striptags()) ``` -------------------------------- ### Convert objects to strings with soft_str Source: https://github.com/pallets/markupsafe/blob/main/docs/escaping.md The soft_str function converts an object to a string while preserving the safety status of existing Markup objects to prevent double-escaping. ```python from markupsafe import soft_str, escape value = escape("") print(soft_str(value)) ``` -------------------------------- ### escape() Function Source: https://context7.com/pallets/markupsafe/llms.txt The `escape()` function converts special HTML characters to their safe equivalents and returns a `Markup` object. It handles various input types and respects objects with an `__html__` method. ```APIDOC ## escape() Function The `escape()` function replaces HTML special characters (`&`, `<`, `>`, `'`, `"`) with their HTML-safe equivalents, returning a `Markup` object. If the input object has an `__html__` method, that method is called instead and its output is assumed to be already safe. ```python from markupsafe import escape # Escape potentially dangerous user input user_input = "" safe_output = escape(user_input) print(safe_output) # Output: <script>alert('XSS')</script> # Numbers and other types are converted to strings and escaped print(escape(42)) # Output: 42 # Objects with __html__ method return their safe representation class SafeLink: def __html__(self): return 'Home' link = SafeLink() print(escape(link)) # Output: Home # Already escaped Markup strings are not double-escaped already_safe = escape("Hello") print(escape(already_safe)) # Output: <em>Hello</em> ``` ``` -------------------------------- ### Markup.striptags() Method Source: https://context7.com/pallets/markupsafe/llms.txt The `striptags()` method removes all HTML tags and comments from a `Markup` string, unescapes HTML entities, and normalizes whitespace. It returns a plain string suitable for text-only display. ```APIDOC ## Markup.striptags() Method The `striptags()` method unescapes HTML entities, removes all HTML tags (including comments), and normalizes whitespace to single spaces. Returns a plain string suitable for display as text-only content. ```python from markupsafe import Markup # Remove HTML tags and normalize whitespace html_content = Markup("Main »\tAbout") plain = html_content.striptags() print(plain) # Output: Main » About # Complex HTML is stripped cleanly complex_html = Markup("""

Welcome

""") print(complex_html.striptags()) # Output: Welcome Home | About # Useful for generating plain text previews article = Markup("

Breaking: Something & something else happened!

") preview = article.striptags() print(preview) # Output: Breaking: Something & something else happened! ``` ``` -------------------------------- ### escape_silent() Function in MarkupSafe Source: https://context7.com/pallets/markupsafe/llms.txt The escape_silent() function is similar to escape() but treats None values as empty strings. It's useful for optional values in templates. It takes a value as input and returns a Markup object with HTML special characters escaped. ```python from markupsafe import escape, escape_silent # Regular escape converts None to string "None" print(escape(None)) # Output: None # escape_silent returns empty Markup for None print(escape_silent(None)) # Output: (empty string) # Useful with optional values def render_user_bio(bio): return Markup("

Bio: {}

").format(escape_silent(bio)) print(render_user_bio("Hello ")) # Output:

Bio: Hello <world>

print(render_user_bio(None)) # Output:

Bio:

# Works normally for non-None values print(escape_silent("')) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.