Bird
0
0

You want to display a user-submitted comment that may contain some safe HTML tags like <b> and <i>, but prevent any scripts or dangerous tags from running. Which Flask approach best achieves this?

hard📝 Application Q15 of 15
Flask - Security Best Practices
You want to display a user-submitted comment that may contain some safe HTML tags like <b> and <i>, but prevent any scripts or dangerous tags from running. Which Flask approach best achieves this?
ASanitize the comment in Python code to allow only safe tags, then mark safe with <code>|safe</code> in template.
BUse <code>{{ comment|safe }}</code> directly to allow all HTML.
CUse <code>{{ comment }}</code> to escape everything, disallowing all HTML tags.
DUse <code>{% raw %}{{ comment }}{% endraw %}</code> to render raw input.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the need for selective HTML allowance

    Allowing only safe tags requires cleaning input to remove scripts but keep tags like and .
  2. Step 2: Use Python sanitization before rendering

    Sanitize the comment in backend code (e.g., with bleach library) to whitelist safe tags, then mark safe in template.
  3. Step 3: Avoid unsafe direct |safe usage

    Directly using |safe without sanitization risks XSS.
  4. Final Answer:

    Sanitize the comment in Python code to allow only safe tags, then mark safe with |safe in template. -> Option A
  5. Quick Check:

    Sanitize first, then use |safe safely [OK]
Quick Trick: Sanitize input in Python, then use |safe to allow safe HTML [OK]
Common Mistakes:
MISTAKES
  • Using |safe without sanitizing user input
  • Escaping everything and losing desired formatting
  • Using {% raw %} which disables escaping completely

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes