nh3 is a Python binding to the Ammonia HTML sanitizer Rust crate, providing fast and configurable whitelist-based HTML sanitization. It is notably faster than pure-Python alternatives like `Bleach`, which it largely replaces since `html5lib` became unmaintained. The library is actively maintained, with its current version 0.3.4, and receives regular updates to both the Python bindings and its underlying Rust components.
pip install nh3Verified import paths — ran on the pinned version, not inferred.
Sanitize an HTML fragment using the default configuration, then customize allowed tags, and finally demonstrate creating a reusable `Cleaner` instance with specific rules for tags, attributes, and URL schemes.
Review `nh3` documentation, especially for `tags`, `attributes`, and `url_schemes` parameters, to match your desired sanitization policy. Consider `nh3.Cleaner` for explicit, reusable configurations.
Always explicitly specify the `tags` and `attributes` you want to allow using the `nh3.clean()` function parameters or by configuring an `nh3.Cleaner` instance. For example, `nh3.clean(html, tags={'p', 'b', 'i'}, attributes={'a': {'href'}})` to define a strict whitelist.Keep `nh3` up-to-date with the latest releases. Monitor the `nh3` GitHub repository and PyPI for security announcements and new versions.
Implement sanitization in Django form fields (e.g., in `to_python`) or consider using a dedicated package like `django-nh3` (if mature) that provides a sanitized model field. Always sanitize user-provided input *before* saving it to the database.
Install the library using pip: `pip install nh3`
Use the `clean` function within the module to sanitize HTML: `nh3.clean(html_string)`
Ensure arguments like `tags`, `clean_content_tags`, and `url_schemes` are passed as Python `set` objects, and `attributes` as a dictionary of `set` objects, as specified in the documentation. For example, `nh3.clean(html_string, tags={'b', 'i'})`No dependency data recorded yet.