Web Security

Libraries for application-layer web security.

Sanitize HTML your users write with nh3, then add a Python web security library for response headers. secure sets CSP and HSTS once for the whole app.

How to choose:

  • User-written HTML, like comments and posts, or code moving off bleach: nh3
  • HTML rendered from user Markdown: nh3, run on the rendered output
  • Security headers like CSP and HSTS, one policy across ASGI and WSGI apps: secure

Listed in editorial order. Click a column to re-sort the whole list.

Press / to search. Tap a tag to filter. Click any row for details.

Search and filter

Results

Row number Tags
Python binding to the ammonia HTML sanitizer, a fast replacement for bleach.
messense/github.com/messense/nh3 / /33,246,010 downloads/month
HTTP security headers for Python web applications with ASGI and WSGI middleware.
TypeError/github.com/TypeError/secure / /1,924,344 downloads/month

Web Security guide

nh3 is a Python binding to ammonia, an allowlist-based HTML sanitizer built to stop cross-site scripting from untrusted user HTML. It parses fragments the same way browsers do. Call nh3.clean() on each fragment, and pass tags and attributes to set what it allows, like tags={"b"}. When you use the same options everywhere, create an nh3.Cleaner once and reuse it. ammonia won't linkify bare URLs or add line breaks, so its docs say to run a markup processor before the sanitizer: render Markdown first, then clean the HTML it outputs.

secure keeps all your security headers in one policy object, instead of header strings copied across handlers and hooks. Start from Secure.with_default_headers(), which its docs call the recommended starting point, configure it once, and reuse it everywhere. Prefer its ASGI or WSGI middleware to cover the whole app, and set headers per response when you're inside an existing hook or view. The defaults are only a starting point: adjust the Content Security Policy for the scripts, styles, and third-party services your app really uses. Then test a stricter policy against the real app before rollout.

Use both, with sanitizing as the main defense. OWASP says to sanitize HTML when users author it, and to treat CSP as an additional layer of defense, never the primary one.

Know a project that belongs here?

Tell us what it does and why it stands out.