Secure Headers for Python Web Frameworks

1.0.1 · active · verified Sat Apr 11

Secure is a lightweight Python library designed to effortlessly add essential HTTP security headers to web applications. It supports multiple frameworks like Flask, FastAPI, and Django with a unified, modern API. The library is actively maintained, with the current stable version being 1.0.1, and a 2.0.0 release candidate introducing significant enhancements and API changes.

Warnings

Install

Imports

Quickstart

This Flask example demonstrates how to integrate `secure.py` by applying default security headers to every response using an `after_request` hook. The `Secure.with_default_headers()` method provides a baseline set of recommended headers.

import os
from flask import Flask, Response
from secure import Secure

app = Flask(__name__)

# Instantiate Secure with default headers (or customize)
# For v2.0.0rc1 and later, consider `Secure.with_preset(Preset.BALANCED)` or middleware.
secure_headers = Secure.with_default_headers()

@app.after_request
def add_security_headers(response: Response):
    secure_headers.set_headers(response)
    return response

@app.route("/")
def home():
    return "Hello, secure world!"

if __name__ == "__main__":
    # In a real application, use a production-ready WSGI server like Gunicorn
    app.run(debug=True)

view raw JSON →