PYTHON
Robust Server-Side Input Validation and Sanitization with Flask
Implement robust server-side input validation and sanitization in a Flask application using `WTForms` for validation and `Bleach` for HTML sanitization to prevent XSS and ensure data integrity.
from flask import Flask, request, jsonify, render_template_string
from wtforms import Form, StringField, IntegerField, TextAreaField, validators
from wtforms.validators import DataRequired, Length, NumberRange
import bleach
app = Flask(__name__)
# Configuration for Bleach to allow safe HTML tags and attributes
ALLOWED_TAGS = ['a', 'p', 'b', 'i', 'strong', 'em', 'br']
ALLOWED_ATTRIBUTES = {'a': ['href', 'title']}
# Define a form for input validation
class CommentForm(Form):
username = StringField('Username', [
DataRequired(),
Length(min=3, max=50, message='Username must be between 3 and 50 characters.')
])
age = IntegerField('Age', [
DataRequired(),
NumberRange(min=13, max=120, message='Age must be between 13 and 120.')
])
comment = TextAreaField('Comment', [
DataRequired(),
Length(min=10, max=500, message='Comment must be between 10 and 500 characters.')
])
@app.route('/')
def index():
# Example of how to render a basic form template
return render_template_string('''
<!doctype html>
<html>
<head><title>Submit Comment</title></head>
<body>
<h1>Submit Your Comment</h1>
<form method="POST" action="/submit">
Username: <input type="text" name="username"><br>
Age: <input type="number" name="age"><br>
Comment: <textarea name="comment"></textarea><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
''')
@app.route('/submit', methods=['POST'])
def submit_comment():
form = CommentForm(request.form)
if form.validate():
# Input is valid, now sanitize
sanitized_username = bleach.clean(form.username.data, strip=True) # strip=True removes disallowed tags entirely
sanitized_comment = bleach.clean(form.comment.data,
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRIBUTES,
strip=True)
sanitized_age = form.age.data # Age is an integer, no HTML to sanitize
# In a real application, save to database etc.
response_data = {
"status": "success",
"message": "Comment received and processed.",
"data": {
"username": sanitized_username,
"age": sanitized_age,
"comment": sanitized_comment
}
}
return jsonify(response_data), 200
else:
# Input is invalid
return jsonify({"status": "error", "errors": form.errors}), 400
if __name__ == '__main__':
app.run(debug=True) # Turn debug=False in production
How it works: This Python Flask snippet illustrates robust server-side input validation and sanitization. It uses `WTForms` to define a schema and perform data validation (e.g., presence, length, type, range) on incoming form data, ensuring that only expected and well-formed input is processed. For text fields that might contain HTML, `Bleach` is employed to sanitize the input by stripping disallowed tags and attributes, effectively preventing Cross-Site Scripting (XSS) attacks while allowing a defined set of safe HTML elements.