How to Resolve Python "ModuleNotFoundError: No module named 'flask_cors'"
When developing Flask web applications that need to handle Cross-Origin Resource Sharing (CORS), the Flask-Cors extension is commonly used. If you encounter the ModuleNotFoundError: No module named 'flask_cors', it means Python cannot find this extension when your application tries to import it (usually via from flask_cors import CORS). This almost always indicates that the package is not installed in the active Python environment.
This guide provides a clear walkthrough of the causes and step-by-step solutions to install Flask-Cors correctly.
Understanding the Error: Python's Import System & Flask Extensions
Python uses its import system (sys.path) to locate modules. When you write from flask_cors import CORS, Python searches for a package named flask_cors. Flask-Cors is a third-party extension for Flask, not part of the standard library or Flask itself, so it needs to be installed separately using a package manager like pip. The ModuleNotFoundError occurs if the package wasn't installed or was installed into a different Python environment than the one running your Flask application.
Common Causes of the Error
- Package Not Installed: You simply forgot to run
pip install Flask-Cors. - Incorrect Python Environment: The package was installed using a different
pip(linked to a different Python version or environment) than thepythoninterpreter running your Flask app. - Virtual Environment Not Activated: You installed the package globally but are running your app from within a virtual environment (or vice-versa), or you forgot to activate the correct virtual environment before running the app.
- IDE Misconfiguration: Your IDE (VS Code, PyCharm) is configured to use a Python interpreter that doesn't have
Flask-Corsinstalled.