pythonflaskpytestwerkzeug

Why did Flask start failing with "ImportError: cannot import name 'url_quote' from 'werkzeug.urls'"?


Environment:

Python 3.10.11
Flask==2.2.2

I run my Flask backend code in docker container, with BASE Image: FROM pytorch/pytorch:2.0.1-cuda11.7-cudnn8-runtime

But when I run the pytest with version pytest 7.4.2,

pip install pytest
pytest

it raised an Error, with logs:

==================================== ERRORS ====================================
_____________ ERROR collecting tests/test_fiftyone_utils_utils.py ______________
ImportError while importing test module '/builds/kw/data-auto-analysis-toolkit-backend/tests/test_fiftyone_utils_utils.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/conda/lib/python3.10/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_fiftyone_utils_utils.py:2: in <module>
    import daat  # noqa: F401
/opt/conda/lib/python3.10/site-packages/daat-1.0.0-py3.10.egg/daat/__init__.py:1: in <module>
    from daat.app import app
/opt/conda/lib/python3.10/site-packages/daat-1.0.0-py3.10.egg/daat/app/__init__.py:6: in <module>
    from flask import Flask, jsonify, request
/opt/conda/lib/python3.10/site-packages/flask/__init__.py:5: in <module>
    from .app import Flask as Flask
/opt/conda/lib/python3.10/site-packages/flask/app.py:30: in <module>
    from werkzeug.urls import url_quote
E   ImportError: cannot import name 'url_quote' from 'werkzeug.urls' (/opt/conda/lib/python3.10/site-packages/werkzeug/urls.py)

My codes works well when I directly run it with python run.py

run.py shown below

from daat import app

app.run(host='0.0.0.0')

I guess it should be the pytest versions issue, because it used to work well without changing any related code, and I use pip install pytest without defined a specific version.

And my backend runs well without pytest.


Solution

  • I had the same problem. It is because Werkzeug 3.0.0 was released and Flask doesn't specify the dependency correctly (requirements says Werkzeug>=2.2.0). This is why, Werkzeug 3.0.0 is still installed and Flask 2.2.2 isn't made for Werkzeug 3.0.0.

    Solution: Just set a fix version for Werkzeug such as Werkzeug==2.2.2 in your requirements.txt and it should work.