Ошибка modulenotfounderror no module named flask

After reading title of this post, don’t try to make duplicate first because herewith content may be asked in different way. Btw, I’m very new in python and start learning now for work requirement.

here are my dependencies

virtualenv --version => 15.0.2

pip --version => 19.0.3

flask --version => 1.0.2, Python 2.7.10 (default, Aug 17 2018, 19:45:58)

python --version => 3.7.1

And, here is my source code of main.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, World!"

Problem is following error encountered when I render like python main.py

Traceback (most recent call last): File «main.py», line 1, in

from flask import Flask ModuleNotFoundError: No module named ‘flask’

But when I render like FLASK_APP=main.py flask run, it was working. Please let me know how’s difference between python ... and FLASH_APP= ...

The error “ModuleNotFoundError: No module named flask» is a common error experienced by data scientists when developing in Python. The error is likely an environment issue whereby the flask package has not been installed correctly on your machine, thankfully there are a few simple steps to go through to troubleshoot the problem and find a solution.

Your error, whether in a Jupyter Notebook or in the terminal, probably looks like one of the following:

No module named 'flask'
ModuleNotFoundError: No module named 'flask'

In order to find the root cause of the problem we will go through the following potential fixes:

  1. Upgrade pip version
  2. Upgrade or install flask package
  3. Check if you are activating the environment before running
  4. Create a fresh environment
  5. Upgrade or install Jupyer Notebook package

Are you installing packages using Conda or Pip package manager?

It is common for developers to use either Pip or Conda for their Python package management. It’s important to know what you are using before we continue with the fix.

If you have not explicitly installed and activated Conda, then you are almost definitely going to be using Pip. One sanity check is to run conda info in your terminal, which if it returns anything likely means you are using Conda.

Upgrade or install pip for Python

First things first, let’s check to see if we have the up to date version of pip installed. We can do this by running:

pip install --upgrade pip

Upgrade or install flask package via Conda or Pip

The most common reason for this error is that the flask package is not installed in your environment or an outdated version is installed. So let’s update the package or install it if it’s missing.

For Conda:

# To install in the root environment 
conda install -c anaconda flask 

# To install in a specific environment 
conda install -n MY_ENV flask

For Pip:‌

# To install in the root environment
python3 -m pip install -U Flask

# To install in a specific environment
source MY_ENV/bin/activate
python3 -m pip install -U Flask

Activate Conda or venv Python environment

It is highly recommended that you use isolated environments when developing in Python. Because of this, one common mistake developers make is that they don’t activate the correct environment before they run the Python script or Jupyter Notebook. So, let’s make sure you have your correct environment running.

For Conda:

conda activate MY_ENV

For virtual environments:

source MY_ENV/bin/activate

Create a new Conda or venv Python environment with flask installed

During the development process, a developer will likely install and update many different packages in their Python environment, which can over time cause conflicts and errors.

Therefore, one way to solve the module error for flask is to simply create a new environment with only the packages that you require, removing all of the bloatware that has built up over time. This will provide you with a fresh start and should get rid of problems that installing other packages may have caused.

For Conda:

# Create the new environment with the desired packages
conda create -n MY_ENV python=3.9 flask 

# Activate the new environment 
conda activate MY_ENV 

# Check to see if the packages you require are installed 
conda list

For virtual environments:

# Navigate to your project directory 
cd MY_PROJECT 

# Create the new environment in this directory 
python3 -m venv MY_ENV 

# Activate the environment 
source MY_ENV/bin/activate 

# Install flask 
python3 -m pip install Flask

Upgrade Jupyter Notebook package in Conda or Pip

If you are working within a Jupyter Notebook and none of the above has worked for you, then it could be that your installation of Jupyter Notebooks is faulty in some way, so a reinstallation may be in order.

For Conda:

conda update jupyter

For Pip:

pip install -U jupyter

Best practices for managing Python packages and environments

Managing packages and environments in Python is notoriously problematic, but there are some best practices which should help you to avoid package the majority of problems in the future:

  1. Always use separate environments for your projects and avoid installing packages to your root environment
  2. Only install the packages you need for your project
  3. Pin your package versions in your project’s requirements file
  4. Make sure your package manager is kept up to date

References

Conda managing environments documentation
Python venv documentation

When using Python, a common error you may encounter is modulenotfounderror: no module named ‘flask’. This error occurs when Python cannot detect the Flask library in your current environment. Flask does not come with the default Python installation. This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.


Table of contents

  • ModuleNotFoundError: no module named ‘flask’
    • What is ModuleNotFoundError?
  • What is Flask?
    • How to install Flask on Windows Operating System
    • How to install Flask on Mac Operating System
    • How to install Flask on Linux Operating System
      • Installing pip for Ubuntu, Debian, and Linux Mint
      • Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
      • Installing pip for CentOS 6 and 7, and older versions of Red Hat
      • Installing pip for Arch Linux and Manjaro
      • Installing pip for OpenSUSE
    • Check Flask Version
  • Installing Flask Using Anaconda
  • Testing Flask
  • Summary

ModuleNotFoundError: no module named ‘flask’

What is ModuleNotFoundError?

The ModuleNotFoundError occurs when the module you want to use is not present in your Python environment. There are several causes of the modulenotfounderror:

The module’s name is incorrect, in which case you have to check the name of the module you tried to import. Let’s try to import the re module with a double e to see what happens:

import ree
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
1 import ree

ModuleNotFoundError: No module named 'ree'

To solve this error, ensure the module name is correct. Let’s look at the revised code:

import re

print(re.__version__)
2.2.1

You may want to import a local module file, but the module is not in the same directory. Let’s look at an example package with a script and a local module to import. Let’s look at the following steps to perform from your terminal:

mkdir example_package

cd example_package

mkdir folder_1

cd folder_1

vi module.py

Note that we use Vim to create the module.py file in this example. You can use your preferred file editor, such as Emacs or Atom. In module.py, we will import the re module and define a simple function that prints the re version:

import re

def print_re_version():

    print(re.__version__)

Close the module.py, then complete the following commands from your terminal:

cd ../

vi script.py

Inside script.py, we will try to import the module we created.

import module

if __name__ == '__main__':

    mod.print_re_version()

Let’s run python script.py from the terminal to see what happens:

ModuleNotFoundError: No module named 'module'

To solve this error, we need to point to the correct path to module.py, which is inside folder_1. Let’s look at the revised code:

import folder_1.module as mod

if __name__ == '__main__':

    mod.print_re_version()

When we run python script.py, we will get the following result:

2.2.1

Lastly, you can encounter the modulenotfounderror when you import a module that is not installed in your Python environment.

What is Flask?

Flask is a lightweight web framework written in Python. It does not automatically come installed with Python. The simplest way to install Flask is to use the package manager for Python called pip. The following instructions to install Flask are for the major Python version 3.

How to install Flask on Windows Operating System

You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.

python get-pip.py

You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.

pip --version

To install Flask with pip, run the following command from the command prompt.

pip3 install flask

How to install Flask on Mac Operating System

Open a terminal by pressing command (⌘) + Space Bar to open the Spotlight search. Type in terminal and press enter. To get pip, first ensure you have installed Python3:

python3 --version
Python 3.8.8

Download pip by running the following curl command:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

The curl command allows you to specify a direct download link. Using the -o option sets the name of the downloaded file.

Install pip by running:

python3 get-pip.py

From the terminal, use pip3 to install Flask:

pip3 install flask

How to install Flask on Linux Operating System

All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.

Installing pip for Ubuntu, Debian, and Linux Mint

sudo apt install python-pip3

Installing pip for CentOS 8 (and newer), Fedora, and Red Hat

sudo dnf install python-pip3

Installing pip for CentOS 6 and 7, and older versions of Red Hat

sudo yum install epel-release

sudo yum install python-pip3

Installing pip for Arch Linux and Manjaro

sudo pacman -S python-pip

Installing pip for OpenSUSE

sudo zypper python3-pip

Once you have installed pip, you can install flask using:

pip3 install flask

Check Flask Version

Once you have successfully installed Flask, you can use two methods to check the version of Flask. First, you can use pip show from your terminal.

pip show flask
Name: Flask
Version: 1.1.2
Summary: A simple framework for building complex web applications.
Home-page: https://palletsprojects.com/p/flask/
Author: Armin Ronacher
Author-email: [email protected]
License: BSD-3-Clause
Location: /Users/Yusufu.Shehu/opt/anaconda3/lib/python3.8/site-packages
Requires: Werkzeug, Jinja2, itsdangerous, click
Required-by: 

Second, within your python program, you can import Flask and then reference the __version__ attribute:

import flask

print(flask.__version__
1.1.2

Installing Flask Using Anaconda

Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda, you can install flask using the following command:

conda install -c anaconda flask

Testing Flask

Once you install Flask, you can test it by writing a hello world script. To do this, first, create a file called flask_test.py and add the code below to the file:

from flask import Flask

app = Flask(__name__)


@app.route('/')

def hello_world():

    return 'Hello, World!'

if __name__ == '__main__':

    app.run()

Save and close the file, then run it from the command line using:

python flask_test.py

You will get something similar to the following output:

 * Serving Flask app "flask_test" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

This output informs you that you can interact with your web application by going to the above URL. Go to http://127.0.0.1:5000/, and “Hello, World!” will appear on the page.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on Flask, go to the article:

  • How to Solve Python ModuleNotFoundError: no module named ‘flask_cors’

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

The ModuleNotFoundError: No module named 'flask' error happens in Python when the flask module can’t be imported. You may forget to install the flask module or it can’t be found in your Python environment.

To fix this error, you need to make sure that the flask module exists and can be found. This article will show you how.

Installing flask

Suppose you have a script named app.py with the following content:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

When you run the script using Python, the following error shows up:

Traceback (most recent call last):
  File ...
    from flask import Flask
ModuleNotFoundError: No module named 'flask'

To fix this error, you need to install the flask module using pip, the package installer for Python.

Use one of the following commands depending on where you do the installation:

# Use pip to install flask
pip install flask

# Or pip3
pip3 install flask

# If pip isn't available in PATH
python -m pip install flask

# Or with python3
python3 -m pip install flask

# For Windows without pip in PATH
py -m pip install flask

# for Anaconda
conda install -c anaconda flask

# for Jupyter Notebook
!pip install flask

Alternatively, you can install it using the requirements.txt file if you have one in your project.

You can use the requirements.txt file with pip as follows:

pip install -r requirements.txt

# or
pip3 install -r requirements.txt

Once installed, run the script that imports the flask module again to see if the error has been resolved.

If you still see the error, that means the Python interpreter you used to run the script can’t find the module you installed.

One of the following scenarios may happen in your case:

  1. You have multiple versions of Python installed on your system, and you are using a different version of Python than the one where flask is installed.
  2. You might have flask installed in a virtual environment, and you are not activating the virtual environment before running your code.
  3. Your IDE uses a different version of Python from the one that has flask installed

Let’s see how to fix these errors.

Case#1 — You have multiple versions of Python

If you have multiple versions of Python installed on your system, you need to make sure that you are using the specific version where the flask package is installed.

You can test this by running the which -a python or which -a python3 command from the terminal:

$ which -a python
/opt/homebrew/bin/python
/usr/bin/python

In the example above, there are two versions of Python installed on /opt/homebrew/bin/python and /usr/bin/python.

Suppose you run the following steps in your project:

  1. Install flask with pip using /usr/bin/ Python version
  2. Install Python using Homebrew, now you have Python in /opt/homebrew/
  3. Then add from flask import Flask in your code

The steps above will cause the error because flask is installed in /usr/bin/, and your code is probably executed using Python from /opt/homebrew/ path.

To solve this error, you need to run pip install flask command again so that the package is installed and accessible by the new Python version.

Finally, keep in mind that you can also have pip and pip3 available on your computer.

The pip command usually installs module for Python 2, while pip3 installs for Python 3. Make sure that you are using the right command for your situation.

Next, you can also have the package installed in a virtual environment.

Case#2 — You are using Python virtual environment

Python venv package allows you to create a virtual environment where you can install different versions of packages required by your project.

If you are installing flask inside a virtual environment, then the module won’t be accessible outside of that environment.

Even when you never run the venv package, Python IDE like Anaconda and PyCharm usually create their own virtual environment when you create a Python project with them.

You can see if a virtual environment is activated or not by looking at your command prompt.

When a virtual environment is activated, the name of that environment will be shown inside parentheses as shown below:

In the picture above, the name of the virtual environment (base) appears when the Conda virtual environment is activated.

To solve this, you can either:

  1. Turn off the virtual environment so that pip installs to your computer
  2. Install the flask in the virtual environment with pip

You can choose the solution that works for your project.

When your virtual environment is created by Conda, run the conda deactivate command. Otherwise, running the deactivate command should work.

To activate your virtual environment, use one of the following commands:

# For Conda:
conda activate <env_name>

# For venv:
source <env_name>/bin/activate

For Pycharm, you need to follow the Pycharm guide to virtual environment.

Case#3 — IDE using a different Python version

Finally, the IDE from where you run your Python code may use a different Python version when you have multiple versions installed.

For example, you can check the Python interpreter used in VSCode by opening the command palette (CTRL + Shift + P for Windows and ⌘ + Shift + P for Mac) then run the Python: Select Interpreter command.

You should see all available Python versions listed as follows:

You need to use the same version where you installed flask so that the module can be found when you run the code from VSCode.

If you use Pycharm, follow the Pycharm configuring Python interpreter guide.

Once done, you should be able to run the from flask import Flask script in your code.

Conclusion

To conclude, the ModuleNotFoundError: No module named 'flask' error occurs when the flask package is not available in your Python environment.

To fix this error, you need to install flask using pip.

If you already have the module installed, make sure you are using the correct version of Python, activate the virtual environment if you have one, and check for the Python version used by your IDE.

By following these steps, you should be able to import flask modules in your code successfully.

Please follow the guide below

  • You will be asked some question, please read them carefully
  • Put an x into all the boxes [ ] relevant to your issue (like this: [x])
  • Use the Preview tab to see what your issue will actually look like

Make sure you are using the latest version: run git pull to update your version from Lyndor directory

Before submitting an issue make sure you have:

  • At least skimmed through the README

What is the purpose of your issue?

  • Bug report (encountered problems with Lyndor) 🪲
  • Feature request (request for a new functionality) ☝️
  • Question ❓ unable to open the setting page
  • Other

If the purpose of this issue is a bug report, or you are not completely sure then provide the full terminal output as follows:

Copy the whole output and insert it here. It should look similar to one below (replace it with your log inserted between triple «`):

python settings/settings.py
Traceback (most recent call last):
  File "settings/settings.py", line 6, in <module>
    from flask import Flask, request, jsonify, render_template
ModuleNotFoundError: No module named 'flask'


Answer questions related to your Environment which will help in reproducing the issue:

The issue was encountered on: 💻

  • [x ] MacOS
  • Windows
  • Linux

Login method:

  • Regular login (username + password)
  • Organization login (cookies.txt)
  • cookies.txt + Library login(for exercise file)

Enter the python version you are using for download. Find your python version by typing in terminal python -V

  • python (3.6)

If the purpose of this issue is a bug report please provide all kinds of example URLs where you encountered issues (replace following example URLs by yours):


Description of your issue, suggested a solution and other information

Explanation of your issue in arbitrary form goes here. Please make sure the description is worded well enough to be understood. Provide as much context and examples as possible.

Понравилась статья? Поделить с друзьями:
  • Ошибка minimum system requirement not met
  • Ошибка module not found excel
  • Ошибка minimal bash like line editing is supported
  • Ошибка module datetime has no attribute strptime
  • Ошибка minecraft не удалось подключиться к миру