0
0
Flaskframework~30 mins

XSS prevention in templates in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
XSS Prevention in Flask Templates
📖 Scenario: You are building a simple Flask web app that shows user comments on a page. Users can submit comments, and you want to make sure the comments are safe to display without allowing harmful scripts to run.
🎯 Goal: Build a Flask app that safely displays user comments by preventing cross-site scripting (XSS) attacks using Flask's template autoescaping features.
📋 What You'll Learn
Create a list of user comments with some containing HTML tags
Add a variable to hold a new user comment
Render the comments safely in a Flask template using autoescaping
Add a final route to display the comments page
💡 Why This Matters
🌍 Real World
Web applications often display user-generated content. Preventing XSS attacks is critical to keep users safe and maintain trust.
💼 Career
Understanding how to safely render user input in templates is a key skill for web developers working with Flask or similar frameworks.
Progress0 / 4 steps
1
Create the initial comments list
Create a list called comments with these exact string entries: 'Hello, world!', 'Nice to meet you.', and ''.
Flask
Need a hint?

Use square brackets to create a list and include the exact strings with quotes.

2
Add a new user comment variable
Create a variable called new_comment and set it to the string 'Welcome to the site!'.
Flask
Need a hint?

Assign the exact string to the variable new_comment using an equals sign.

3
Render comments safely in a Flask template
Write a Flask route function called show_comments that returns the rendered template 'comments.html' passing the comments list and new_comment variable. Use Flask's render_template function.
Flask
Need a hint?

Use the @app.route('/') decorator and define the function with the exact name show_comments. Return render_template with the template name and variables.

4
Complete the comments.html template with autoescaping
Create a Jinja2 template named comments.html that loops over the comments list and displays each comment inside a <li> tag. Also display the new_comment in a separate <p> tag. Use Jinja2's default autoescaping to prevent XSS.
Flask
Need a hint?

Use Jinja2 template syntax with {% for %} to loop and {{ }} to display variables safely.