- Fix Python ModuleNotFoundError: No module named ‘flask’
- Installing flask
- Case#1 — You have multiple versions of Python
- Case#2 — You are using Python virtual environment
- Case#3 — IDE using a different Python version
- Conclusion
- Take your skills to the next level ⚡️
- About
- Search
- Flask — WSGI — No module named ‘flask’
- Python : No module named ‘flask’
Fix Python ModuleNotFoundError: No module named ‘flask’
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:
When you run the script using Python, the following error shows up:
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:
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:
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.
- 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.
- You might have flask installed in a virtual environment, and you are not activating the virtual environment before running your code.
- 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:
In the example above, there are two versions of Python installed on /opt/homebrew/bin/python and /usr/bin/python .
- Install flask with pip using /usr/bin/ Python version
- Install Python using Homebrew, now you have Python in /opt/homebrew/
- 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.
- Turn off the virtual environment so that pip installs to your computer
- 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:
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.
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.
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Flask — WSGI — No module named ‘flask’
I’ve been following Sentdex’ Flask tutorial. He’s using a Venv to set up his Flask, but didn’t set his Python up to work with a Venv. I’ve tried installing Flask globally — yet it still doesn’t work. Trying to browse to the server returns a 500 Internal Server Error I’m getting the usual no module named flask error. errorFGL.log
[Sun Feb 05 11:22:32.043925 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] mod_wsgi (pid=26340): Target WSGI script '/var/www-fgl/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module. [Sun Feb 05 11:22:32.044105 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] mod_wsgi (pid=26340): Exception occurred processing WSGI script '/var/www-fgl/FlaskApp/flaskapp.wsgi'. [Sun Feb 05 11:22:32.044243 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] Traceback (most recent call last): [Sun Feb 05 11:22:32.045011 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] File "/var/www-fgl/FlaskApp/flaskapp.wsgi", line 8, in [Sun Feb 05 11:22:32.045070 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] from FlaskApp import app as application [Sun Feb 05 11:22:32.045549 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] File "/var/www-fgl/FlaskApp/FlaskApp/__init__.py", line 1, in [Sun Feb 05 11:22:32.045594 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] from flask import Flask [Sun Feb 05 11:22:32.045689 2017] [wsgi:error] [pid 26340:tid 118578538694400] [client 86.52.205.25:49814] ImportError: No module named 'flask'
from flask import Flask app = Flask(__name__) @app.route('/') def homepage(): return "Success" if __name__ == "__main__": app.run()
#!/usr/bin/python import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www-fgl/FlaskApp/") from FlaskApp import app as application application.secret_key = '[REDACTED]'
ServerName [REDACTED] WSGIScriptAlias / /var/www-fgl/FlaskApp/flaskapp.wsgi Require all granted Alias /static /var/www-fgl/FlaskApp/FlaskApp/static Require all granted ErrorLog $/errorFGL.log LogLevel warn CustomLog $/accessFGL.log combined
Python : No module named ‘flask’
So i’ve been stuck on this problem for a while now. For one file I have it is working and it is allowing me to use the flask framework. with this code.
from flask import Flask, render_template from flask import request from flask import * from datetime import datetime from functools import wraps import time import csv app = Flask(__name__) app.secret_key ='lukey' #displays index page @app.route('/') def home(): return render_template('index.html') #displays welcome page @app.route('/welcome') def welcome(): return render_template('welcome.html') #allows user to login @app.route('/log', methods=['GET','POST']) def log(): error = None if request.method == "POST": if request.form['user'] != 'admin' or request.form['pass'] != 'admin': error = "Invalid credentials" else: session['logged_in'] = True return redirect (url_for('welcome')) return render_template('log.html', error=error) #allows user to logout @app.route('/logout') def logout(): session.pop('logged_in', None) flash('you were logged out') return redirect (url_for('log')) #function to check if admin is logged in def login_required(test): @wraps(test) def wrap(*args, **kwargs): if 'logged_in' in session: return test(*args, **kwargs) else: flash('you need to login before using admin tools') return redirect(url_for('log')) return wrap #Displays map @app.route('/map') def map(): return render_template('map.html') #Displays gallery @app.route('/gallery') def gallery(): return render_template('gallery.html') #Allows users to view previous bookings @app.route('/bookings', methods = ['GET']) def bookings(): bookingsFile ='static\\bookings.csv' data = readFile(bookingsFile) return render_template('bookings.html', data=data) #Allows user to request for a booking @app.route('/addBookings', methods = ['POST']) def addBookings(): bookingsFile = 'static\\bookings.csv' data = readFile(bookingsFile) bookingName = request.form[('name')] bookingEmail = request.form[('email')] bookingDate= request.form[('date')] #Converts the date string to unix timestamp bookingDateUnix = time.mktime(datetime.strptime(request.form[('date')], "%Y-%m-%d").timetuple()) numberOfDays = request.form[('days')] #calculates the end date in unix form endDateUnix = int(numberOfDays)*24*60*60+int(bookingDateUnix) #converts the unix form end date to string newDate = datetime.fromtimestamp(int(endDateUnix)).strftime('%Y-%m-%d') #Calculates the price of the users stay price = int(numberOfDays) * 200 #Will be changed by admin to confirm bookings hasBeenBooked = 'Awaiting confirmation' bookingsFile ='static\\bookings.csv' for row in data: prevBookingDateUnix = row[7] prevEndDateUnix = row[8] #Testing no double bookings if row[2] == bookingDate or row[6] == newDate: flash('This time has already been allocated') return redirect(url_for('bookings')) #Testing there are no crossover points elif float(prevBookingDateUnix) < bookingDateUnix and float(prevEndDateUnix) < bookingDateUnix and bookingDateUnix < endDateUnix: flash('valid input') else: flash('invalid input') return redirect(url_for('bookings')) #parameters parsed from input newEntry =[bookingName, bookingEmail, bookingDate, numberOfDays, hasBeenBooked, price, newDate, bookingDateUnix, endDateUnix] data.append(newEntry) writeFile(data, bookingsFile) return render_template('bookings.html', data=data) #allows viewing of comments in csv file @app.route('/comments', methods = ['GET']) def comments(): commentsFile = 'static\\comments.csv' data = readFile(commentsFile) return render_template('comments.html', data=data) #adding comments to csv file @app.route('/addComments', methods = ['POST']) def addComments(): # add an entry to the data #read the data from file commentsFile = 'static\\comments.csv' data = readFile(commentsFile) #add the new entry commentorsName = request.form[('commentorsName')] comment = request.form[('comment')] commentDate = datetime.now().strftime("%Y-%m-%d / %H:%M") newEntry = [commentorsName, comment, commentDate] data.append(newEntry) #save the data to the file writeFile(data, commentsFile) return render_template('comments.html', data=data) #Ensures the administrator is logged in before comments are deleted @app.route('/deleteComments', methods = ['POST']) @login_required def deleteComments(): f = open('static\\comments.csv', 'w') f.truncate() f.close() return render_template('comments.html') #Ensures the administrator is logged in before bookings are deleted @app.route('/deleteBookings', methods = ['POST']) @login_required def deleteBookings(): f = open('static\\bookings.csv', 'w') f.truncate() f.close() return render_template('bookings.html') def readFile(aFile): #read in 'aFile' with open(aFile, 'r') as inFile: reader = csv.reader(inFile) data = [row for row in reader] return data def writeFile(aList, aFile): #write 'aList' to 'aFile' with open(aFile, 'w', newline='') as outFile: writer = csv.writer(outFile) writer.writerows(aList) return if __name__ == '__main__': app.run(debug = True)
#!/usr/bin/python3.4 # # Small script to show PostgreSQL and Pyscopg together # from flask import Flask, render_template from flask import request from flask import * from datetime import datetime from functools import wraps import time import csv import psycopg2 app = Flask(__name__) app.secret_key ='lukey' def getConn(): connStr=("dbname='test' user='lukey' password='lukey'") conn=psycopg2.connect(connStr) return conn @app.route('/') def home(): return render_template(index.html) @app.route('/displayStudent', methods =['GET']) def displayStudent(): residence = request.args['residence'] try: conn = None conn = getConn() cur = conn.cursor() cur.execute('SET search_path to public') cur.execute('SELECT stu_id,student.name,course.name,home_town FROM student,\ course WHERE course = course_id AND student.residence = %s',[residence]) rows = cur.fetchall() if rows: return render_template('stu.html', rows = rows, residence = residence) else: return render_template('index.html', msg1='no data found') except Exception as e: return render_template('index.html', msg1='No data found', error1 = e) finally: if conn: conn.close() #@app.route('/addStudent, methods =['GET','POST']') #def addStudent(): if __name__ == '__main__': app.run(debug = True)
I feel like the problem is going to be something to do with the versions of python/flask/pip i'm using. Any ideas thank you.