Flask is not importing even though I installed it - python

I'm on Windows 10 and I am using PyCharm to run my application. I'm pretty new to Python and just coding in general.
I typed:
pip install flask
in the cmd prompt but forgot to open cmd prompt under administrator privileges. Could this be the problem? I ended up re-opening the cmd prompt with administrator rights and typed
pip install flask
again and it showed that it was already installed. I'm pretty sure I have flask installed on my system.
When I try to run the python file below which I named test_webapp.py I get the following error:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
I get an error:
ModuleNotFoundError: No module named 'flask'
when i type in python --version into the command prompt i get version 3.6.3.
When i type the same code into the Python 3.6 (32-bit) command line, the code works! However, when i try to run it using the IDLE I get a SyntaxError and the number 6 in Python 3.6.3 gets highlighted in red.
Any ideas as to what's going on?

Try to install flask with specific version of python, do something like:
python[version] -m pip install flask
Note: replace [version] with python version (such as python3).

Sounds like the pip you are using is not installing for the same python you are using.
try which pip and which python
the they should be in the same folder. Might want to make an alias or two if you have a bunch of pythons (sys, 2, 3, conda etc) or just start with a fresh virtual env for your project. <- best imo.

When you typed pip install flask in the command prompt, it installed flask in the global environment. That is the reason when you run it in command line it works because it used global environment by default.
Pycharm has a virtual environment, therefore you need to install it in that virtual environment. Open Pycharm, then open the terminal within Pycharm and type "pip install flask".
You can read about virtual environment in python to get a clear idea.

Check version of python
python --version
And then use accordingly
if python 3.x.x then type
python3 app.py
if python 2.x.x then type
python2 app.py

Related

no module called "flask"

I'm currently trying to run a file called forum.py in the vagrant directory but it returns an ImportError: No module named flask. After I logged out vagrant, when I type flask --version, the python version is 3.9.1 and the flaks version is 2.0.2. When I check the python version in vagrant, it returns 2.7.12. When I type flask-version, it returns flask: command not found. Does it mean the flask is installed to python 3.9 but not 2.7? Moreover, when I make a new directory in IDE for the files, should I choose Python3.9 or Python2.7 as my interpreter?
Ideally, together with your file, you have a requirements.txt for you to install the project dependencies on your machine, or better yet, on your virtual environment
Btw, if you are going to use your Global version of Python... Try to use the most current version.
Try the command: python3 forum.py

"ModuleNotFoundError: No module named 'kivymd'" in .spec file

I already did pip install kivymd in my Python project. I also had the kivymd directory in my project.
I'm working with a Mac.
I created a spec file called "coinsnack4.spec" including the code below:
from kivymd import hooks_path as kivymd_hooks_path
However, when I try to package my python project with the spec file with the command:
pyinstaller -y --clean --windowed coinsnack4.spec
I got the error below:
File "coinsnack4.spec", line 3, in <module>
from kivymd import hooks_path as kivymd_hooks_path
ModuleNotFoundError: No module named 'kivymd'
I really don't know why this happens because I already pip install kivymd. I don't know what to do next and I would appreciate if anyone could help me with this error.
Thank you very much!
Why are you facing this issue?
The reason behind this is the concept of virtual environments in python. Each virtual environment is independent of the other. You can use different virtual environments, activate and deactivate them as per your project's requirements.
I would suggest you go through this doc once Python venv
As when you do a `pip install <SOME_PACKAGE> from your local terminal, it installs the package from into the default python environment and from the terminal itself (not pycharm terminal) if you try to execute the python program it will work fine but as soon as you switch to pycharm or any other IDE, it has it's own python environment set and that environment is unaware of what happened in the other python environment. So you need to install the pip package here also, in order to execute the same python program.
Solution:-
The first thing I would suggest is to install the package in the virtual environment that the pycharm is using. For that click on the Terminal icon the below bar of your pycharm window. then do run the below command :-
python3 -m pip install kivymd
If this doesn't work, try configuring the python environment in pycharm.
Below is how you can change or update your python interpreter in pycharm: -
Setting an existing Python interpreter
At any time, you can switch your Python interpreter either using the Python Interpreter selector or in the Project Settings/Preferences.
Creating a new Python interpreter
To add a new interpreter to the current project:
If you have a conda environment, follow the below steps: -
Or if you want to setup a new virtual environment, do as below: -
I think you installed pyinstaller not in project's virtualenv, just:
pip install pyinstaller
then problem will be fixed.

Installing custom packages inside a python venv

I need to install some custom python tools into my python virtual environment. I can install them fine globally.
The venv was created by running python3 -m venv env
My files are laid out like this:
tool/
|-setup.py
project/
|-env/
|-|-bin/
I've installed globally by going to tool/ and running python3 setup.py this works great and I can then open a python terminal and type import tool and everything works.
So now I need to use it in the virtual env. First thing I tried was navigating to project/env/bin and running python3 ~//tool/setup.py which didn't throw errors but when I enter a python shell and try import tool I get the error ImportError: No module named 'tool'
Next I tried activating the venv with source evn/bin/activate navigating to tool/ and installing just like I would globally by running python3 setup.py which again throws no errors and gives a success message but doesn't work in a python shell.
My questions are: is this at all the correct way to install something into a venv when not using pip? and if so, what did I break and how can I fix my setup to work?

Flask ImportError: No Module Named Flask

I'm following the Flask tutorial here:
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I get to the point where I try ./run.py and I get:
Traceback (most recent call last):
File "./run.py", line 3, in <module>
from app import app
File "/Users/benjaminclayman/Desktop/microblog/app/__init__.py", line 1, in <module>
from flask import Flask
ImportError: No module named flask
This looks similar to:
ImportError: No module named flask
But their solutions aren't helpful. For reference, I do have a folder named flask which one user mentioned may cause issues.
Try deleting the virtualenv you created. Then create a new virtualenv with:
virtualenv flask
Then:
cd flask
Now let's activate the virtualenv
source bin/activate
Now you should see (flask) on the left of the command line.
Edit: In windows there is no "source" that's a linux thing, instead execute the activate.bat file, here I do it using Powershell: PS C:\DEV\aProject> & .\Flask\Scripts\activate)
Let's install flask:
pip install flask
Then create a file named hello.py (NOTE: see UPDATE Flask 1.0.2 below):
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
and run it with:
python hello.py
UPDATE Flask 1.0.2
With the new flask release there is no need to run the app from your script. hello.py should look like this now:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
and run it with:
FLASK_APP=hello.py flask run
Make sure to be inside the folder where hello.py is when running the latest command.
All the steps before the creation of the hello.py apply for this case as well
For python 3 use
pip3 install flask
The only way I could solve was by adding my users python dir to myapp.wsgi file. As an example:
sys.path.append('/home/deployer/anaconda3/lib/python3.5/site-packages')
I guess that if you install the packages in the global enviroment, you should have no problem, but I had my python packages installed as user.
After activating the virtual environment and installing Flask, I created an app.py file. I run it like this : python -m flask run. Hope this will help!
I had a similar problem with flasgger.
The reason for that was that I always use
sudo pip install flask
but for some reason that's not always the way to go.
Sometimes, you have to do just
pip install flask
Another gotcha is that sometimes people type pip install Flask with the cap F
Posting this here in case somebody gets stuck.
Let me know if it helped.
Useful Link:
What is the difference between pip install and sudo pip install?
this is what worked for me,
sudo -H pip install flask
Or for pip3(python3) use :
sudo -H pip3 install flask
Sidenote
If you're using virtualenv it's a good idea to
pip freeze >> requirements.txt
to allow for the installed packages to be listed in one place.
The sudo command and -H flag. For more on sudo's -H flag, look at Paul's answer.
Hope this helps you.
Another thing - if you're using python3, make sure you are starting your server with python3 server.py, not python server.py
This is what worked for me when I got a similar error in Windows:
Install virtualenv:
pip install virtualenv
Create a virtualenv:
virtualenv flask
Navigate to Scripts and activate the virtualenv:
activate
Install Flask:
python -m pip install flask
Check if flask is installed:
python -m pip list
I was using python2 but installed this:
sudo apt-get install libapache2-mod-wsgi-py3
Instead of:
sudo apt-get install libapache2-mod-wsgi
Correcting the installation solved the no flask problem.
Edit
/etc/apache2/sites-available/FlaskApp.conf
Add the following two lines before the "WSGIScriptAlias" line:
WSGIDaemonProcess FlaskApp python-home=/var/www/FlaskApp/FlaskApp/venv/FlaskApp
WSGIProcessGroup FlaskApp
Restart Apache:service apache2 restart
I'm following the Flask tutorial too.And I met the same problem.I found this way to fix it.
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
In my case the solution was as simple as starting up my virtual environment like so:
$ venv/scripts/activate
It turns out I am still fresh to Python :)
Go to the flask file in microblog, then activate the virtual environment with source bin/activate, then go to flask/bin and install flask, and the rest of the packages, pip install flask. You will see flask listed inside bin directory. Try to run ./run.py again from microblog (or from wherever you have the file).
Even i too suggest u virtualenv,
This might also solve ur problem.
sudo apt install python-flask
If u want to deploy in productionserver then go ahead with above solution else use virtualenv.
If you are using Pycharm then this is the virtual environment issue.
So, at the time of creating your Python project you will have to select "Existing interpreter" option -> click "system Interpreter" -> select the correct option for example "*\AppData\Local\Programs\Python\Python3.6\python.exe".
You can use 'New Virtual Env' as well, but I have just given the quick fix that should work for Pycharm users.
The simplest answer to this problem is specifying the correct path to flask in your environment. Make sure the script you are running knows how to get to the flask installation. Using print(sys.path) as mentioned above certainly helped to figure out the path(s) the script was using.
enter your python interactive mode
then:
import sys
sys.path
it will print your path. Check wether flask is installed in the sys.path.
For MacOS, python path is under
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
But pip'll install python package by default under
/Library/Python/2.7/site-packages
That's why it doesn't work for MacOS.
The flask script is nice to start a local development server, but you would have to
restart it manually after each change to your code. That is not very nice and Flask can
do better. If you enable debug support the server will reload itself on code changes,
and it will also provide you with a helpful debugger if things go wrong.
To enable debug mode you can export the FLASK_DEBUG environment variable before
running the server:
forexample your file is hello.py
$ export FLASK_APP=hello.py
$ export FLASK_DEBUG=1
$ flask run
in my case using Docker, my .env file was not copied, so the following env vars were not set:
.env.local:
FLASK_APP=src/app.py
so in my Dockerfile i had to include:
FROM deploy as dev
COPY env ./env
which was referenced in docker-compose.yml
env_file: ./env/.env.local
another thing i had to pay attention to is the path variable to ensure my environment is used
ENV PATH $CONDA_DIR/envs/:my_environment_name_from_yml_file:/bin:$CONDA_DIR/bin:$PATH```
my answer just for any users that use Visual Studio Flesk Web project :
Just Right Click on "Python Environment" and Click to "Add Environment"
I had a similar problem using WSL and PyCharm / VSCode, the problem only occurred in the development environment and not in production. I realized that IDE's with WSL can have problems when exporting PYTHONPATH from their work directory and I started to do it manually.
Before running your program and inside a VENV, try running the following command:
export PYTHONPATH="path/my_user/code"
In your case , the solution is :
First:
Open the terminal and navigate to the directory/folder where that python file is located ( in ur case the python file you created is run.py) and make sure you have installed flask in that same directory/folder.
Second :
Now , type the following command :
$python3 "pythonfilename" (in ur case, its $python3 "run.py")
I had the same error where it said flask module not found. this is what I did:
used venv to create a virtual environment $ python3.6 -m venv --without-pip virtual
activated the virtual environment using source virtual/bin/activate
downloaded pip into the virtual environment curl https://bootstrap.pypa.io/get-pip.py | python
installed flask using pip install flask
after running my application, all was good.
you first need to create a Python Environment
like this:
py -m venv YOUR_DIR_NAME
You can also try this workaround set FLASK_DEBUG=1 && python -m flask run
It worked for me
It worked for me after upgrading pip:
curl https://bootstrap.pypa.io/get-pip.py | python
Found that answer here: https://stackoverflow.com/a/49748494/3197202
Then I could just install flask:
pip install flask

No module named flask using virtualenv

I am following these steps to learn flask http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world/page/0#comments
I ran this command to create the virtual env:
python virtualenv.py flask
When I try to start flask using the python.exe file in my project scripts directory, it says
No module named flask
My PATH is set to the python directory that virtualenv installed. Why is it not able to find flask?
I initially started with the official Flask quickstart guide and was able to get the webserver to run, but with this virtual env install it is not working.
Make sure your virtualenv is activated. Then You check on the PYTHONPATH of that virtualenv. Is there a flask package (folder) installed in that directory.
If you unsure whether you have installed flask, just run the following command to see all the packages you have installed pip list or pip show flask. Do you see flask there? If not you can run pip install flask
This error can also appear if you start your Flask python server using ./run.py or similarly use file associations to start your server. Then the python command in the association will be used instead of your virtual environment python command. Use python run.py instead. See how my run.py innocently assumes /usr/bin/python?
#!/usr/bin/python
# run.py
from app import app
app.run(debug=True,host='0.0.0.0',port=5000)
I had this same problem on three Raspberry Pi units at the same time; beat my head against the wall trying to fix it for several hours (reinstall flask via pip, apt and aptitude - no joy).
Instead of:
pip install flask
I finally tried:
pip install Flask
Worked like a charm.
Make sure you run your script after you've activated your virtualenv. On OS X you'd see (virtual_env_name) at the start of each terminal line. To do this:
cd to your virtualenv's directory and type . bin/activate
cd to the directory containing the .py file you want to run at app launch in the browser
Now enter python file_name.py, for me the file name was routes.py following this example
This problem can also arise if the port is not available.
Try running on different port.
Activate your virtual environment first with
source bin/activate envName
Then try to run your command again
If nothing else helps, check that in your code it is:
from flask import Flask
I've tried many things before I've noticed my mistake. I had this in my code:
from Flask import Flask
When I have changed capitalized letter for the module name, i.e. flask then everything worked.
On Windows even if you see (virtual_env_name) in the cmd line it is possible that the virtual environment is not completely activated. Deactivate/reactivate and try again.
I am running Python on windows 7. I had same problem No module named flask.
I tried reinstalling python, venv but it did not work.
Finally i run it like this
Install venv the usual way
go to scripts directory and activate
C:\Python34\microb>c:\Python34\microb\fla\scripts\python run.py
here microb is my project and fla is venv
In Python 3.x
pip3 install flask
Worked fine for me.
Thanks & Regards
For those of you on Windows who are running into this problem, have activated your venv and flask is installed in the right directory. For me I realized it was looking for flask but the file was called flask.exe. I renamed it and it worked perfectly.
Try below lines :
$ python3.7 -m venv env
$ source env/bin/activate
(env)$ pip install yourpackages
(env)$ python app.py

Categories

Resources