Pycharm can't recognize Flask - python

I am writing a flask application with PyCharm. But Pycharm couldn't recognize Flask module. Flask installed globally on my computer as seen on screenshot. I tried virtualenv also but nothing change. Still can't find Flask. I can run Flask anywhere except Pycharm succesfully. My operating system is Windows by the way.
Here is my code snippet
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route("/")
#app.route("/home")
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True)

Change the name of your file from flask.py to something else and it will work. Naming your file flask.py causes Python to look in your file for the Flask class, and it fails.

Naming a file site.py causes this issue.
It looks like a module named "site" is involved in importing the installed libraries, so by creating a module of the same name I prevent flask from being discovered.
Renaming my file from site.py to something else fixed the issue for me.

Related

Cannot find Reference methodName in 'imported module ModuleName' in PyCharm, how can i fix this problem?

i have a strange experience with Python code, so:
Im trying to learn Flask with some tutorial, and i managed to follow some with nice result, and now im trying to start my own project to make sure i understood the stuff, but i find myself stuck by hours for this problem
I have this directory structure:
/projectName/
/venv/
/website/
/static/
/templates/
/__init__.py
/otherPython.py
/app.py
app.py
from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
init.py
from flask import Flask
def create_app():
# I create the app and give the secret key
app = Flask(__name__)
app.config['SECRET_KEY'] = 'stackoverflow'
return app
The Problem
Cannot find reference 'create_app' in 'imported module website'
Enviroment:
Win10 pro 10.0.19045
python 3.10
PyCharm 2022.1.4 (community edition)
Does somebody have any clue on what im missing, or if im allucinating and dont see a clear code/path error?
In a identical project it works, i already tryied to mark ProjectFolder as Source Root, already tryed to clean caches and restart, and i cannot understand why as a identical import with same folder structura and method name, in one project work(the tutorial one), and now in mine doesnt.
I dont know if that is helpfull but after from website import if i do ctrl+space i do not see the init.py file nor the create_app() method.

python flask import. import error unknown location

i am trying to import create_app from init.py that is located in the website file
but everytime I try to run the code I get
ImportError: cannot import name 'create_app' from 'website' (unknown location)
this is my files
.vscode
env
website
--static
--templates
--__init__.py
--auth.py
--views.py
--models.py
main.py
init.py
from flask import Flask
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hello'
return app
main.py
from website import create_app
app = create_app
if __name__ == '__main__':
app.run(debug=True)
thought this is the only method that isn't working I tried this method to check if the error is from vscode but it is just from this method
I tried
app.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "hello Flask"
and when I write in the terminal `python -m flask run
I would get a website that says "hello Flask"
but when I press the run icon I get nothing
unlike the first one if I run it I would get an import error unknown location
and if I use python -m flask run I would get
Error: could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module not found in the current directory.
thought everything is sync to Github
in both of them I am working in a 'script' environment
A fix I came up with was adding name to the function defining create_app inside the init file.
Example:
from flask import Flask
def create_app(name):
app = Flask(name)
When importing, try from website.templates import create_app. So basically after you put it to import from website, add . following the sub-folder that you desired to import from (in this case it is templates).
I ran into the same thing, but it appears that these files "models, views, etc" isn't in website folder, they are inside static folder which is in website folder, that's why it's not working.
I just fixed them manually.
For someone getting this error later (like myself), be sure to check that your main package's
__init__.py
file is in the correct place.
You forgot create environment variable.
if you using mac or linux export FLASK_APP=main.py
if you windows set FLASK_APP=main.py
And last in main.py should be app = create_app()
try this
in your main.py
from website.init import create_app
or
change file init to init.py
then in your main.py
from website._init_ import create_app

flask run vs. python

I'm having difficulty getting my flask app to run by using the "python" method. I have no problems using
export FLASK_APP=microblog.py
flask run
but attempting to use
python microblog.py
will result in the following error
ImportError: No module named 'app'
where my microblog.py file looks like this:
from app import app, db
from app.models import User
#app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User}
and my __init__.py file looks like this:
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
from app import routes
if __name__ == '__main__':
app.run()
The folder these files reside in is called 'app'. I've tried putting the
if __name__ == '__main__':
app.run()
In the microblog.py file as well, which was also unsuccessful.
I also have folders for templates/static/etc. and a routes file where I run all my #app.route() commands
Again, everything works fine when I run "flask run" in terminal, it just breaks down when I try using "python microblog.py". I'm trying to launch the app on AWS and just about every tutorial requires the applications to be called using the "python" method. Any help is appreciated.
[Solved]
I had my directories mixed up. I pulled microblog.py back outside of the app folder and was able to run python microblog.py with no issues and without having to edit anything.
In hindsight, I probably should have posted the file structure of everything right in the beginning.
In this line from app import app, db you're trying to import a module called app.app, but it apparently does not exists in your project source.
Try to create a file named app.py inside app/ path, copy and paste all content of __init__.py file inside of it.
Your __init__.py must be blank. It's just indicate that your path app/ is a importable module.
See this article.
I have tried this and it worked for me on windows.
$env:FLASK_APP="hello.py"
flask run
That's it

Initial setup of Flask Mega Tutorial on pythonanywhere

After successfully completing the pythonanywhere flask tutorial (pa.com), Miguel Grinberg's the "Flask Mega Tutorial" (fmt) beckoned. Sadly, I've not even made it to "Hello, World". Here's what I have done:
In pa.com attempting to follow fmt verbatim is a no go:
python3 -m venv flask
leads to an error of
ensurepip is not available
and we do not have sudo access.
Undeterred, I reasoned that all Miguel is asking us to do is distribute the functionality we see in one file in the pa.com tutorial (flask_app.py) into a few files that will make the building of a full app easier. Since pa.com is already setting up my base web app with flask and python 3.4, not being able to set up the virtual env. did not seem to be a block, at least not at first.
Per the fmt, in the base dir of the pa.com (pwd -> home/{username}/microblog) -- which is where the flask_app.py file that successfully generates the pa.com tutorial page lives -- I set up app and tmp directories, and create app/__init__.py, app/views.py and the run.py files as directed by fmt
Hitting the app page (run.py the only file in the main directory) generates an Unhandled Exception on the page.
Changing the name to flask_app.py (which seems to be what pa.com expects on flask installations) generates the same error.
Modifying the content of the flask_app.py code to:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return "working from flask_app.py"
Generates a successful output from the app, whereas having the same code in a file named run.py generates the same Unhandled Exception error.
the lines:
from app import app in both run.py and views.py and
from app import views in __init__.py
all make me wonder... where is this "app" module coming from? But aside from being puzzled by that question, no other ideas on how to proceed from here. Any suggestions? Would really like to get set up on pa.com and work through this tutorial/book.
Feel like I am missing something basic, but not sure what.
First rule is: don't use app.run() on PythonAnywhere - that's what run.py is trying to do. That's fine for your own PC, but on PA it will cause an error. It's fine to have the file there, but don't try and import from that file in your wsgi config.
Instead, you just need to import the flask app variable, which Miguel gets you to put in app/__init__.py (that's slightly confusing, a variable called app, and a folder called app, but we can deal with it!)
To do that, you'll want to add the folder that contains the app folder to your sys.path. You also need to "rename" the app variable to application as you import it:
# assuming we have /home/myusername/microblog/app/__init__.py:
path = '/home/myusername/microblog'
if path not in sys.path:
sys.path.append(path)
# now we can import the app variable from the app folder's __init__
# and rename it to application
from app import app as application
More info: a brief guide to flask on pythonanywhere and a guide to debugging imports and sys.path problems in your pythonanywhere wsgi file
from microblog import app as application
This is fixed my solution.
Best Regards

Flask module does not exist

I downloaded Flask on my Windows system using
pip install flask
it says
Requirement already satisfied.
which makes sense cause i already installed it once before using easy_install.
The official Flask website says, i just need to do this to install. Yet i get the error
ImportError: cannot import name Flask
The code i used is:
from flask import Flask
app = flask.Flask(__name__)
app.debug = True
app.run()
How can i fix this
Not sure if this is the problem, but this code should throw a NameError. If you import the Flask class like this from flask import Flask, then make your app like this app = flask.Flask(__name__), the interpreter will throw a NameError. You never imported flask, only the Flask class. The code should be changed to app = Flask(__name__) since Flask is already in the namespace.

Categories