flask render_template csp

  1. Import the necessary module:
from flask import Flask, render_template
  1. Create a Flask application instance:
app = Flask(__name__)
  1. Define a route for the desired endpoint:
  1. Create a function to handle the route:
def example():
  1. 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'",
  1. Pass the CSP header to the render_template function as a keyword argument:
    return render_template('example.html', csp=csp_header)
  1. In the HTML template (example.html), access and apply the CSP header using the meta tag:
<!DOCTYPE html>
<html lang="en">
    <meta http-equiv="Content-Security-Policy" content="{{ csp }}">
    <!-- Other head elements -->
    <!-- Body content -->

Note: The above example includes a simple CSP header. Adjust the values according to your security requirements.