I've just started developing a new application using Flask and PyCharm as my IDE.
I've encountered a problem which is driving me crazy.
Here is the code. I'll spare use all the import part and so on, I'll show only the routes that cause problems.
#app.route("/")
def home():
return render_template("home.html")
#app.route("/login/")
def login():
return "foo"
The first route works without a problem. However on the first line of the second route, PyCharm gives me an error message '"#" or "def" expected'. This breaks the autoindent and the auto completion features.
But the code runs without a problem.
Can anyone tell me how to fix this?
Thank you
This is because PyCharm is not able to recognize the flask package or version.
Once you add new project to PyCharm -
Go to File menu item
Click on Settings option
This will open-up the pop-up window.
In the left-hand-side link list - click on the project name
Click on the Project Interpreter link
In the right-hand-side pane select Flask and related packages that your project needs and add/install the same.
What worked for me was (I was missing pycharm's python environment dependencies for python)
If you don't already have a requirements file for your project.
Navigate to your project & this on your command line (as I used a venv virtual environment):
(venv)$ pip freeze > requirements.txt
Then Open your pycharm and open the requirements file, wait a second or two and a pop up notification will show up at the top showing you are missing dependencies and will provide you a click here to install.
After that I had no issues.
Related
I use VS Code Version: 1.74.3 on MacOS 13.2. python -V returns Python 3.11.1.
I get the following error message: Import "django.shortcuts" could not be resolved from source Pylance(reportMissingModuleScource).
As you can see in the screenshot, the correct venv is activated and includes Django.
I also tried or checked:
Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10
https://stackoverflow.com/a/65802367/2321643 but
the suggested solution with reloading the windows did not help.
reinstallation the virtual environment within VSCode and installing Django again
re-selecting the venv.
deleting all python-specific settings in user/settings.json as well as .vcode/settings.json.
Reinstallation python and associated extensions.
Using Debug I can safely run my Django-application without any import issues. What do I need to do that Pylance does not issues these problems?
My issue was a bug, fixed and closed.
For reference: https://github.com/microsoft/pylance-release/issues/3881
Try clicking on where it says "3.11.1 ('.venv': venv)" (near the bottom right).
It should bring up a little dialog sort of thing at the top where you can verify that the Python path is correct.
Check that it is using the correct Python path. It should be something like venv/bin/python3 or venv/bin/python assuming venv is situated at the root of youur project.
So i'm studying python crashcourse and after finishing the basics I jumped to the django project.
I created a virtual env, installed django and created an app with manage.py startapp command.
I use Visual Studio Code, and the problem is when I go to models.py it gives an error that it's unable to find django.db module
unable to import error
Now I understand this is because of the file structure, which is as per my research the correct one, and I followed the book carefully, however i don't know how to fix this and I feel that i'm missing something.
This is my file structure for the virtual environment
file structure
Any idea how to fix it ? :)
Thanks in advance
Thank you Incognos !
To be more specific The solution was :
enter "code ." in the terminal and then a new VS opens.
Ctrl+Shift+P -> Select Interpreter
select the environment that starts with ./env or .\env
run Ctrl+Shift+` to activate it
VS is not seeing your virtualenv. You need to activate it for VS code so that it knows that django is installed in the virtualenv see https://code.visualstudio.com/docs/python/environments
it happens because pylint is installed outside your virtual environment. So install pylint inside virtual environment with this command (pip install pylint).
Note: If you're using Visual Studio Code - Insiders you'll use code-insiders . instead of the code . command.
Then, a new window will open and you can set your virtual environment interpreter there.
Reference: https://github.com/Microsoft/vscode/issues/6627
in my case, the problem was solved by opening VS-Code in the directory where virtualenv is located.
Click Ctrl-shift-p to access the Command pallete, then search for Python: Select Interpreter. Click on it and then select on the one that has been recommended by the editor.
(Modified to answer the questions in the first comment.)
I am using Flask in PyCharm and getting different results than when I run it from the terminal. In particular, the working directory of the Python program is different under Pycharm. So this code works correctly when running flask from the command line and the print os.getcwd() displays '/Users/Wes/Dropbox/Programming/Python/etpruncnt2'.
However if I run the same code in Pycharm the os.getcwd() displays '/Applications/PyCharm.app/Contents/bin' and the file open fails
with IOError: [Errno 2] No such file or directory: 'data/results.json'.
The root of the project in PyCharm is /Users/Wes/Dropbox/Programming/Python/etpruncnt2. I have also added a screenshot of the project structure in the PyCharm GUI.
I suppose I must have the configuration wrong in PyCharm. I have included a screenshot.
What should I do?
#app.route('/running_count')
def running_count():
print os.getcwd()
with open('data/results.json', 'r') as resultFile:
resultData = json.load(resultFile)
return str(resultData)
You Only Have Shown Script Path
How is project structure ? When you are creating new project you are telling pycharm the project root and may you mixed that part :)
I am going to close this. The immediate problem is that the Working Directory in the config was not filled in.
Most default setups for PyCharm do fill that in, but the setup for flask does not.
I have filed a low-urgency bug report with IntelliJ.
I've a project in which a python script must get the path to some of its imports from an environment variable. I'm handling this with
sys.path.insert(0, os.environ["PYDIR"])
which works fine when I run the application.
Pylint (in my Vim editor) is flagging import errors on all the modules I import from "PYDIR". I hate to disable the error message in the module since it's usually useful. OTOH, I also hate the visual clutter in my editor.
I suspect there's no good solution since Pylint doesn't execute the code but thought I'd ask anyway.
EDIT: See my below comment on difference between this question and PyLint "Unable to import" error - how to set PYTHONPATH?
For my particular case, the following seems to work satisfactorily. (I'm developing on OS X, I start a customized Terminal shell when working on this project, and my editor is 'mvim' (MacVim))
Add to the Terminal startup shell command list:
source .myprojectshellenv;
where .myprojectshellenv contains:
export PYDIR=path-to-myproject-python-modules
alias pmvim="env PYTHONPATH=$PYDIR mvim"
Then all I need remember is to edit the files with pmvim instead of mvim. (If I forget the error indicators from pylint (via syntastic) make it immediately obvious)
Am new to Flask development and am using an IDE like Pycharm for the first time, so please pardon the ignorance.
So while playing around with a project that I am working on to understand Flask, I created a virtual environment by the name venv. So the tree of my project would look something like :
my_project_directory
Project_specific_directories_and_files
requirements.txt
venv
To activate the virtual env, I used to do venv/bin/activate and my project would run as needed.
I came across virtualevnwrapper later and decided to use that. After installing it and setting it up, I moved over to the virtualenvwrapper way of working with virtual envs and completely removed(deleted) the venv directory from my project structure. The new project structure after deleting venv is as :
my_project_directory
Project_specific_directories_and_files
requirements.txt
Everything works fine. The project runs as expected.
However, now after the venv directory was removed, when I open my project in Pycharm, for my import statements like :
from flask import Flask, render_template, redirect, url_for, request, session, flash # , g
from flask_sqlalchemy import SQLAlchem
all the packages that I try importing gets underlined as error in the Pycharm IDE. I opened the Python console, in Pycharm, trying to debug the error and it gives the following error :
Error:Cannot run program "/Users/my_user_name/Desktop/some_parent_directory/my_project_directory/venv/bin/python" (in directory "/Users/my_user_name/Desktop/some_parent_directory/my_project_directory"): error=2, No such file or directory
Now I thought that apparently Pycharm is still using it's cache. So I tried invalidating the cache and restarting Pycharm as explained here, but the problem was still there.
Now I have 2 questions:
Why is Pycharm behaving this way? I removed the venv directory completely etc. Why is it still referencing the old (venv) location?
If it really is not able to resolve the dependencies, how exactly then is my project running all fine? Shouldn't it break the app?
Ok. After some further digging now, I was able to get the errors flagged in Pycharm rectified. I went to Pycharm -> Preferences -> Project: my_project_directory -> Project Interpreter & found that it was 'for some reason' still pointing to the older venv directory. From the drop down of the 'Project Interpreter:' section, I chose the path to my virtualenv created by virtualenvwrapper & saved the changes by Apply->Ok. This removed the error indications from the code in Pycharm. Although solved, the mystery of what/why was this happening is still unsolved for me. – qre0ct Jul 12 at 17:13
Moreover, I also removed the unused/deleted interpreters from the list of project interpreters by going to the 'more' section in the 'Project Interpreter' part and using the '-' at the bottom to remove the ones not needed.