python3 : Cannot import name flask - python

I tried the following simple code,
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
it is running fine with,
python hello.py
but it gives an error when i try with python3
ImportError: cannot import name 'Flask'

A package is installed against a specific Python version/location. Installing Flask for Python 2 (which is probably what the python and pip commands are aliased to), doesn't install it for Python 3.
You should really just use virtualenv to control exactly what versions and packages you are using.
This creates a Python 3 environment and installs Flask:
virtualenv -p /usr/bin/python3 my_py3_env
source my_py3_env/bin/activate
pip install flask
When you open a new terminal, just source the activate script again to keep using the environment.

Related

Flask fails with "Error: While importing 'X', an ImportError was raised", but does not display the error. How to find the source of the error?

When starting a Flask app with:
$ flask run
I received the error:
Error: While importing 'wsgi', an ImportError was raised.
Usage: flask [OPTIONS] COMMAND [ARGS]...`
...
However, there is no stack trace or other information provided. What is the best way to get the ImportError stack trace?
Import the Flask app at the Python interpreter prompt
To see the ImportError stack trace, open a Python interpreter prompt and import the module that loads the Flask app (usually app.py or wsgi.py). If applicable, be sure that your virtual environment is activated.
$ python
>>> from my_app_folder import app
Set the FLASK_APP environment variable
If you can import the Flask app module using the Python interpreter without error, try setting the FLASK_APP environment variable to point to the Flask app module.
$ FLASK_APP='my_app_folder/app' FLASK_ENV=development flask run
This error can be caused if Flask is unable to import any libraries(in my case it was Flask_restful)
This is the workaround I found to find the missing libraries:-
I found which library was missing by just running the Flask App file (wsgi.py) directly with python
python wsgi.py
which gave an Importerror listing the missing libraries
after finding the missing libraries, simply install libraries using pip, for me Flask_restful was missing so I installed Flask_restful
.
After installing missing libraries simply run the flask app using
flask run
The only thing that I would add to Christopher Peisert's answer is the option that gave me the error messages that I was searching for:
(venv) ~/example_flask_app/$ python
>>> import app
Or in my case
>>> import microblog

Python "ModuleNotFoundError: No module named 'flask'"

I am a beginner with the python programming.
I have python 3 installed in my local system.
I coding along as part of a tutorial video and as part of the tutorial, i have created a virtual environment and created an app.py file with the below content.
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, World!"
if __name__ == "__main__":
app.run()
I have installed all the dependencies like flask and pytest in the virtual environment as per the tutorial using gitbash.But when i run the command python3 app.py in gitbash i get the below error message
File "C:\path\Python\python-github-actions-example\src\app.py", line 1, in <module>
from flask import Flask
ModuleNotFoundError: No module named 'flask'
(myvenv)
I checked the python version and it is python 3.9.7
If i run python app.py i get the output.
Why is it not running even though correct version is installed
Any idea why ?
Try to delete the venv or make a new one.
Then create a new venv like this:
virtualenv flask
Go to the flask directory
: cd flask
Activate it: scripts\activate
You should see (flask) on the left of the command line.
Install flask again: pip install flask
Run your file again.
Some times you need to change/select de versiĆ³n/env if you after installed. like it if work for you.
After you do what #kmogi says in their post above, start the app with python not python3.

Can not import a module when run the flask server using the flask run command

I'm new to flask framework and I want to write a simple flask app that uses another python module (librosa package). I have successfully installed librosa in the same virtual environment that I have installed flask and I can easily import it in the python interpreter. Here is the python script.
# app.py
from flask import Flask
import librosa
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello'
if __name__ == '__main__':
app.run()
The problem is that when I want to run the flask app using the flask run command (after setting export FLASK_APP=app.py) I get the ModuleNotFoundError error as follows:
Error: While importing "app", an ImportError was raised:
Traceback (most recent call last):
File "/home/masoud/anaconda3/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/home/masoud/projects/my_projects/seperator_rewriten/app.py", line 2, in <module>
import librosa
ModuleNotFoundError: No module named 'librosa'
The strange thing is that there is no import error when I run the flask server using python app.py command.
if you are using an IDE such as pycharm, then you may need to install it from the terminal in the IDE itself, not cmd
This may be the solution to your problem:
python -m flask run
The reason is that flask run may use the python executable somewhere else, not the virtual environment you created for the project.
You can add these lines of code in your script:
import sys
import flask
print(sys.executable)
print(flask.__version__)
And then you can check the python executable path using python app.py and flask run.

App runs locally, fails in PyPi with ModuleNotFound

I added the src/sample/run.py below to the sampleproject. It runs locally (prints "add_one(2) = 3"), but deployed pip version fails:
virtualenv venv
source venv/bin/activate
pip install -i https://test.pypi.org/simple/ sampleproject-valhuber
sample-run
ModuleNotFoundError: No module named 'simple'
Here is src/sample/run.py:
import simple # FAILS in PyPi: ModuleNotFoundError...
def main():
print("add_one(2) = " + str(simple.add_one(2)))
if __name__ == '__main__':
main()
The complete code, along with packaging procedure is on this GitHub project.
Your simple.py is inside sample package. You have to import it from the package:
import sample.simple
or
from sample import simple

How to use virtualenv and pip in python

I'd like to have a python script which in the beginning create a virtual environment, install required modules (e.g. cherrypy) and then continues with the rest of the code.
What I found so far is as follow:
import os, virtualenv
HOME_DIRECTORY = "venv"
virtualenv.create_environment(HOME_DIRECTORY)
execfile(os.path.join(HOME_DIRECTORY, "bin", "activate_this.py"))
import pip
pip.main(["install", "--prefix", HOME_DIRECTORY, "cherrypy"])
import cherrypy
class Root(object):
#cherrypy.expose
def index(self):
return "Hello World!"
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/')
The script creates virtual environment and install cherrypy (based on the log), but still I get ImportError: No module named cherrypy error.
I also tried the following, but got the same error:
import importlib
CHERRYPY = 'cherrypy'
try:
importlib.import_module(CHERRYPY)
except ImportError:
import pip
pip.main(["install", "--prefix", HOME_DIRECTORY, CHERRYPY])
finally:
globals()[CHERRYPY] = importlib.import_module(CHERRYPY)
Apart from the above problem, also, I'd like to know how to specify the python version (e.g. python 3.6) while creating virtual environment. Thanks.
For the record the issue was with the virtual environment activate (the line to execute activate_this.py). For Python 3 the following worked for me:
ACTIVATE_THIS = 'venv/bin/activate_this.py'
exec(Path(ACTIVATE_THIS).read_text(), dict(__file__ = ACTIVATE_THIS))

Categories

Resources