Performance: XSS prevention in templates
This affects page security and user experience by preventing malicious scripts from running, which can indirectly impact rendering and interaction performance.
from flask import Flask, render_template_string app = Flask(__name__) @app.route('/') def index(): user_input = '<script>alert("XSS")</script>' return render_template_string("<p>{{ user_input }}</p>", user_input=user_input)
from flask import Flask, render_template_string app = Flask(__name__) @app.route('/') def index(): user_input = '<script>alert("XSS")</script>' return render_template_string(f"<p>{user_input}</p>")
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct user input injection without escaping | Normal DOM nodes | Potential multiple reflows if scripts modify DOM | High paint cost if scripts run | [X] Bad |
| User input safely escaped by Flask templates | Normal DOM nodes | Single reflow on render | Normal paint cost | [OK] Good |
{{ }}?{{ }} to prevent scripts from running.user_input in a Flask template to prevent XSS?{{ user_input }} automatically escapes content, preventing XSS.|safe filter disables escaping and should be used only with trusted content.<p>User comment: {{ comment }}</p>comment contains <script>alert('XSS')</script>, what will be the rendered HTML output?{{ }}.<script> tags become <script> in raw HTML, but browsers render them as <script> text, not executable code.<p>Message: {{ message|safe }}</p>message contains user input?|safe filter tells Flask not to escape the content, rendering raw HTML.message is user input, malicious scripts can run, causing XSS attacks.<b> and <i>, but prevent any scripts or dangerous tags from running. Which Flask approach best achieves this?|safe without sanitization risks XSS.Pass the test and this pattern moves unknown