# Fix "ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security'"

Yes. An agent swaps Werkzeug's removed safe_str_cmp for hmac.compare_digest, keeps the str and bytes handling callers rely on, runs the tests and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/fix-werkzeug-safe-str-cmp-import-error/werkzeug/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts from the traceback, because the frame that raises decides the fix. In a Flask extension like cryptojuice/flask-scrypt the import is the project's own: line 13 of `flask_scrypt.py` reads `from werkzeug.security import safe_str_cmp`, and the only call is the last line of `check_password_hash`, which compares a stored hash with a freshly computed one. The module fails at import, so `test_scrypt.py` dies on its line 7 before any of its four Python 3 cases is collected.

It then works out why the error appears now. `requirements.txt` pins `Werkzeug==0.15.3`, but `setup.py` declares `install_requires=['Flask', 'scrypt']` with no bounds, and `travis.txt` asks for `Flask>=0.10.1`. Anyone who installs the package, as opposed to the pinned file, gets the newest Flask and whatever Werkzeug that Flask requires. Werkzeug 2.0 marked the function deprecated and its docstring said it would be removed in 2.1. The agent installs both ways in clean virtual environments and records which Werkzeug each one resolved, so the pull request can say that the pin was hiding the problem.

The replacement is `hmac.compare_digest`, and the module already has `import hmac` on line 11, plus a `_builtin_safe_str_cmp = getattr(hmac, 'compare_digest', None)` assignment that nothing reads. The agent does not make a blind one-word swap. Werkzeug's helper encoded any `str` argument to UTF-8 before comparing, and `generate_password_hash` here returns the bytes that `base64.b64encode` produces. A caller who loads the hash from a text column passes a `str`, and `hmac.compare_digest` raises `TypeError` when one side is `str` and the other is bytes. So the agent keeps the encode step for the stored hash, adds a test that checks a password against a `str` hash, and deletes the unused assignment.

Last, it lists what it saw and left alone. The README's usage line imports from `flask.ext.scrypt`, a namespace that current Flask does not have. `.travis.yml` tests Python 2.6, 2.7 and 3.3 and installs with `--use-mirrors`. Those are real, and they belong in their own pull requests.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This project fails with: ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security'. Fix it. First read the full traceback and say whether the failing import is in this repository or inside an installed package; never edit files under site-packages. Read every dependency file (requirements files, setup.py or pyproject.toml, CI install steps) and report how Werkzeug and Flask are constrained in each, then install the project in two clean virtual environments, once from the pinned file and once from the package metadata, and report the Werkzeug version each resolved and whether the import works. Find every use of safe_str_cmp. Replace it with hmac.compare_digest while keeping the behaviour callers had: the old helper accepted str or bytes on either side and encoded str as UTF-8, and hmac.compare_digest raises TypeError on a str and bytes pair, so check what types each call site can receive and encode where needed. Add a test for each type combination a caller can pass. Remove code the change leaves unused. Run the test suite on the newest Werkzeug and on the oldest version the dependency files still allow, and quote both summaries. List anything else you find that is broken on current Flask but unrelated to this error, without fixing it. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with a small diff in the module and a larger one in the tests. In the module, the Werkzeug import is gone, the comparison is `hmac.compare_digest` on two byte strings, and the dead `_builtin_safe_str_cmp` line is removed. In the test file there are new cases for a hash passed as bytes and as `str`. The description quotes the two install reports, pinned and unpinned, with the Werkzeug version each got, then the test summary on each.

A reviewer checks the comparison first. It has to stay constant-time, which rules out a rewrite to `==`, and it has to accept what the old function accepted. The second check is the dependency story: the pull request should not answer this error by adding `Werkzeug<2.1` to `install_requires`, since the code no longer needs Werkzeug at all for this function. When the agent finds that the failing frame is in a third-party package instead, the result is different: a report naming the package, the release that dropped the import, and a version bump with the tests run against it.

## Run it on every error-tracker issue with this ImportError

This error shows up at process start, on the first deploy that rebuilt the image without a lock file, so an error tracker records one issue per service. Most trackers sign their own webhook requests and cannot send the `Authorization: Bearer` header that a Rush `webhook` trigger needs. A small handler on your server sits between the two: it receives the tracker's delivery, keeps issues whose message contains `cannot import name 'safe_str_cmp'`, and posts the payload to the trigger's URL with the trigger's secret. The automation's saved prompt is the instruction, and the stack trace arrives after it as event text.

Have the handler send an `Idempotency-Key` header to the trigger's URL, built from the tracker's issue id, so a redelivered event starts nothing new. Several services often share one base image and fail together; the automation's max runs per hour decides how many of those start at once, and the rest wait for room in the hour.

## Why run it on Rush?

The fix is three lines, and the proof is two installs. Whether the error reproduces depends on which file the environment was built from, and a laptop usually has a virtual environment that was built months ago from the pinned file and still works. The run builds both environments from nothing in its own sandbox, so the difference between `requirements.txt` and `setup.py` is on the record as command output, and the transcript keeps every `pip` resolution and test summary.

It is also a security-adjacent line. The call compares password hashes, and the two easy mistakes are replacing it with `==` or shipping a version that throws `TypeError` for callers who store hashes as text. A run that writes the type tests before it changes the comparison, and shows them passing, gives the reviewer something firmer than a diff that looks right.

## Frequently asked questions

### What replaced safe_str_cmp?

`hmac.compare_digest` from the standard library. Werkzeug's own deprecation message named it as the replacement, and in its last releases the helper was a thin wrapper that encoded `str` arguments to UTF-8 and then called it. The standard function does not do that encoding for you.

### The traceback points into flask_jwt or another extension, not my code. What then?

Then the import cannot be fixed in your repository, and the agent does not patch installed packages. It names the extension and checks whether a newer release dropped the import. When the extension is unmaintained, it reports that and proposes either a maintained replacement or the narrowest Werkzeug pin that keeps the service starting, and says which it chose and why.

### Why not pin Werkzeug below 2.1?

A pin works until Flask is upgraded, because each Flask release sets its own minimum Werkzeug and the resolver will then refuse the combination. In a library, a pin in `install_requires` also pushes the conflict onto every application that installs it. Removing the one import costs less than carrying the pin.

### Does the change still work on old Werkzeug versions?

Yes, since the code stops importing from Werkzeug for this comparison. `hmac.compare_digest` is in the standard library of every Python 3 version still in use. The agent runs the tests on the oldest Werkzeug the dependency files allow as well as the newest, and quotes both results.

## More Werkzeug jobs

- [Fix "ImportError: cannot import name 'url_quote' from 'werkzeug.urls'"](https://getrush.ai/run/fix-werkzeug-url-quote-import-error/werkzeug/)
- [Fix "AttributeError: module 'werkzeug' has no attribute '__version__'" in Flask Tests](https://getrush.ai/run/fix-werkzeug-version-attribute-error/werkzeug/)
- [Fix ValueError: Invalid hash method 'sha256' After a Werkzeug Upgrade](https://getrush.ai/run/fix-invalid-hash-method-sha256/werkzeug/)

## More jobs like this: Fix a bug from an alert

- [Fix "TypeError: __init__() got an unexpected keyword argument 'size'" in gensim 4](https://getrush.ai/run/fix-word2vec-unexpected-keyword-argument-size/gensim/)
- [Fix "RuntimeError: Working outside of application context" from db.create_all() in Flask-SQLAlchemy 3](https://getrush.ai/run/fix-working-outside-of-application-context/flask-sqlalchemy/)
- [Fix "AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK'" From pyOpenSSL](https://getrush.ai/run/fix-x509-v-flag-cb-issuer-check-attribute-error/pyopenssl/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
