flask render_template csp
- Import the necessary module:
from flask import Flask, render_template
- Create a Flask application instance:
app = Flask(__name__)
- Define a route for the desired endpoint:
@app.route('/example')
- Create a function to handle the route:
def example():
- Define a content security policy (CSP) header using the
Content-Security-Policy
response header:
csp_header = {
'default-src': "'self'",
'style-src': "'unsafe-inline'",
'script-src': "'unsafe-inline' 'self'",
}
- Pass the CSP header to the
render_template
function as a keyword argument:
return render_template('example.html', csp=csp_header)
- In the HTML template (
example.html
), access and apply the CSP header using themeta
tag:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Security-Policy" content="{{ csp }}">
<!-- Other head elements -->
</head>
<body>
<!-- Body content -->
</body>
</html>
Note: The above example includes a simple CSP header. Adjust the values according to your security requirements.