Escape HTML entities to prevent Cross-Site Scripting attacks.
Code
Generalimport html
# Escape HTML entities to prevent XSS
return html.escape(user_input)Parameters
Untrusted user input (try a malicious payload)
What is XSS?
Cross-Site Scripting (XSS) occurs when untrusted data is included in a web page without proper escaping. An attacker can inject malicious scripts that execute in other users' browsers.
# DANGEROUS: Directly embedding user input in HTML
template = f"<div>Welcome, {user_input}!</div>"
# If user_input is "<script>alert('XSS')</script>", the script executes!
Why Escaping Works
The html.escape() function converts dangerous characters to HTML entities:
| Character | Escaped | Why |
|---|---|---|
< | < | Prevents opening tags |
> | > | Prevents closing tags |
" | " | Prevents breaking out of attributes |
' | ' | Prevents breaking out of attributes |
& | & | Prevents entity injection |
# SAFE: Escaped output
safe_html = f"<div>Welcome, {html.escape(user_input)}!</div>"
# Renders as text, not executable HTML
Use in Templates
Most Python web frameworks auto-escape by default:
# Jinja2 (Flask) - auto-escapes by default
{{ user_input }} # Safe!
# To render raw HTML (dangerous!):
return {{ user_input | safe }} # Only if you trust the input!
The Rule
Always use html.escape() when embedding untrusted data in HTML. Let your template engine auto-escape when possible.
More Python Snippets
Hash SHA-256
Generate a SHA-256 hash of a string.
SQL Injection Prevention
Use parameterized queries to prevent SQL injection attacks.
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.