The problem
I start a flask app, which works fine when I use "run" or "debug." However, I got the error when use "profile," here is the log message
In folder C:/Users/Myname/PycharmProjects/ProjectName
"C:\Users\Myname\Anaconda3\envs\ProjectName\python.exe" "C:\Program Files\JetBrains\PyCharm
Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py" 127.0.0.1 12055 -m flask run
Starting cProfile profiler
Traceback (most recent call last):
Snapshot saved to C:\Users\Myname/.PyCharm2019.2/system\snapshots\ProjectName1.pstat
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 173, in <module>
profiler.run(file)
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 89, in run
execfile(file, globals, globals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\prof_util.py", line 30, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\Myname\Anaconda3\envs\ProjectName\lib\site-packages\flask\__init__.py", line 19, in <module>
from . import json
ImportError: attempted relative import with no known parent package
What I have tried
I google it and found that it is an old problem.
Can't profile module using relative imports
Pycharm profile is not working
How to reproduce it
If you would like to reproduce it, you can create a flask app using pycharm, and then click "profile."
The default code for flask app is as follows. But I don't think it matters.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
The error message can be different due to the change of the flask version or Pycharm version, but the reason is the same: File "xxx\lib\site-packages\flask\__init__.py", line 19, in <module> use relative import and cause the ImportError
My question
My question is, is there a way to make it work? Any hacks or tricks are also appreciated. I just want to use the profile now. Thank you
Apparently this is a long-standing issue with PyCharm's profiler, it does not run packages correctly resulting in sys.path being wonky and relative imports failing: https://youtrack.jetbrains.com/issue/PY-28509
I guess an option would be to make your own "launcher script" simply copying what flask.__main__ does.
Though things might also work out if you run -m flask.cli instead of just -m flask (I don't know, I didn't test it): it does the same thing but does not invoke a __main__ file so it could behave better.
[New solution]
Thanks to #Masklinn, use -m flask.cli instread of -m flask could solve this problem. However, the configuration in pycharm flask use -m flask by default and I cannot find out a way to modify it. Therefore, I suggest to use pycharm python. The script path should be set to your FLASK_APP, and add -m flask.cli in addtional options.
[Obsolete solution]
One solution is that directly modify the __init__.py to make it work. For example, change
from . import json
from .app import Flask
to
from flask import json
from flask.app import Flask
Related
I am trying to run my python app on my website, and so I've created a virtual environment for all of the packages, and I've correctly installed all of the packages I need. When I check on the file path to my installed packages, they are all pointing to the correct path, and when I got to my site-packages file that they point to, they are all there.
However,
Every time I try to run my app, I get this:
stdin: is not a tty
Traceback (most recent call last):
File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in <module>
app_module = load_app()
File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app
return imp.load_source('passenger_wsgi', startup_file)
File "/home/dsmproto/testblockchain/passenger_wsgi.py", line 1, in <module>
import main as application
File "/home/dsmproto/testblockchain/main.py", line 2, in <module>
from wallet import wallet
File "/home/dsmproto/testblockchain/wallet.py", line 1, in <module>
from Cryptodome.PublicKey import RSA
ImportError: No module named Cryptodome.PublicKey
I know that the module is there, but for some reason it is still saying there's no module.
Is there a command I can use in my SSH to check where my app is looking for modules?
All of the modules I have installed are installed correctly. Furthermore, when I open the SSH and run python commands in the terminal, they are able to import all of the modules without any issues.
So how come my app can't find these modules? Is there a way to check to make sure they are looking in the right place?
Thanks in advance for the help
EDIT:
I ran a script in python to look at the sys.path and got this:
/opt/alt/python38/lib64/python38.zip
/opt/alt/python38/lib64/python3.8
/opt/alt/python38/lib64/python3.8/lib-dynload
/home/dsmproto/virtualenv/testblockchain/3.8/lib64/python3.8/site-packages
/home/dsmproto/virtualenv/testblockchain/3.8/lib/python3.8/site-packages
Those are the correct folders that my packages are installed in, yet when I try to run my app, it still says it can't find them.
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.
I have recently run into an import error with psutils in the types.py called from google.cloud.pubsub_v1 on a GAE standard project inside Pycharm. I messed around for a day trying to find away around it, but no go. psutil imports in python run from the terminal and the console and from a vanilla python project but not from a GAE project. To double up on this I made a basic test of the two as seen below: Both using the same virtualenv...
Standard Vanilla Python Project:
main.py contains
import psutil
def x():
print "hello world"
if __name__ == "__main__":
x()
Google App Engine Project -
main.py contains
import webapp2
import psutil
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.write('Hello world!')
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
The import in the vanilla python project works fine, but the import in the GAE app returns the traceback:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/Users/chez 1/google-app-engine-projects/untitled/main.py", line 18, in <module>
import psutil
ImportError: No module named psutil
Has anyone had similar problems and found a fix?
You're likely having the psutil package installed on your local system (thus working in terminal/console), but not vendored into your app (i.e installed in your app's lib dir) as required for standard env apps (the SDK emulates the real GAE, for which whatever is installed into your local python installation means nothing). From Installing a third-party library:
Create a directory to store your third-party libraries, such as lib/.
mkdir lib
Use pip (version 6 or later) with the -t <directory> flag to copy the libraries into the folder you created in the previous
step. For example:
pip install -t lib/ <library_name>
So just vendor into your app the psutil package.
In my experience this and similar 'No module named ...' errors have been caused by an incorrectly defined python interpreter. See the answers at: ImportError: No module named 'bottle' - PyCharm
My Flask Application is crashing when I'm trying to access it.
This is similar error to this or this. However, my set-up seems correct.
flask.cli.NoAppException: The file/path provided (server) does not appear to exist. Please verify the path is correct. If app is not on PYTHONPATH, ensure the extension is .py
My environment variable correctly set.
export FLASK_APP=server.py
export FLASK_DEBUG=1
My server file is server.py, and I don't have any __init__.py in the directory.
I don't recall having change anything special in the code. Where does the bug could come from?
The issue was that some package were missing or corrupted.
I reinstalled everything with pip3 install -r requirements.txt --ignore-installed and now it works fine.
This error may be a sign that an import is not found.
To see which import is missing, try to run your server.py file with the python interpreter:
python yourapp.py
Example of output :
Traceback (most recent call last):
File "yourapp.py", line 4, in <module>
from flask_httpauth import HTTPBasicAuth
ImportError: No module named flask_httpauth
Source (and other leads)
For me, solution was fixing a misspelled function name "create_app" in my _ init _.py
from flask import Flask
def create_app(test_config=None):
app = Flask(__name__)
return app
Super late answer, but I just ran into this and the solution was to use a Remote WSL connection in VS Code. I thought I was in the correct folder, but VS Code was looking at a very similar folder in Windows. You can tell you're in the wrong folder by running "touch somefile.abc" in your linux terminal, from the project folder, but that file doesn't automatically appear in VS Code's folder structure.
https://code.visualstudio.com/docs/setup/linux
https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl
I am running the following code
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
and getting the following error
Traceback (most recent call last):
File "test.py", line 1, in <module>
from flask import Flask
File "/home/pi/programs/flask.py", line 1, in <module>
from flask import Flask
ImportError: cannot import name Flask
I have tried installing flask through various methods , but still the problem persists
also, is there any alternative to flask???
I ran into this error because I named the test file as flask.py and tried to run it! It creates namespace conflict with the real flask module!
Delete the local test file that you named flask.py and the respective flask.pyc. Give some other name! This will happen with other modules like socket etc where you are likely to give the same name for the test file as the standard module :-)
The reason is your python file name is flask.
Just run apt-get install python3-flask
Edited to install the python3 version, since nobody should be using python2 now.
Just rename flask.py file also delete flask.pyc file
It's because of the name flask.py. It will import itself if the name is flask.py. Change the name and try again.
Restart virtual environment
$ virtualenv flask
Into dir flask run
$source ./bin/activate
Install python module again
$pip install "module"
I had the same issue. Apparently you can't name your file socket.py either.
exactly when we create file name as flask.py and then execute it for the first time it will execute and at the same time framework creates another file called flask.pyc .Now stop the process and start it again it will throw this error as instead of looking to actual framework flask file it is looking in to the one you created . To solve this problem
Go to the folder you created flask.py and delete flask.pyc and then rename flask.py to some test_1.py ..save it and execute it . You should see no errors .
Add PYTHONPATH to your environment:
export PYTHONPATH=/root/environments/my_env/lib/python3.6/site-packages/