python flask import. import error unknown location - python

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

Related

Confused by all the different ways to start & configure a flask app

I've followed different tutorials to learn flask, and lately I've been trying do build something more substantial. I run my flask app with flask run. I have a app.py but no __init__.py. FLASK_APP is not set. I understand that because there's no FLASK_APP, flask looks for app.py by default. Here's the entirety of app.py:
from flask import Flask, redirect, url_for
from os import getenv
from dotenv import load_dotenv
from extensions import db, mail
from projects import por
from requests import requests
load_dotenv()
app = Flask(__name__)
def create_app():
print ('IN CREATE APP')
#SQL Alchemy
app.config['SQLALCHEMY_DATABASE_URI'] = getenv('SQLALCHEMY_DATABASE_URI', None)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = getenv('SQLALCHEMY_TRACK_MODIFICATIONS', False)
# WT-Forms
app.config['SECRET_KEY'] = 'Temporary secret key'
app.config['WTF_CSRF_TIME_LIMIT'] = None
#######
db.init_app(app)
mail.init_app(app)
app.register_blueprint(por)
app.register_blueprint(requests)
#app.route('/', methods=['GET'])
def index():
return redirect(url_for('por.por_no_sm'))
# if __name__ == "__main__":
# create_app().run()
I have 3 specific questions:
If I try to start the app with python app.py, I get ModuleNotFoundError: No module named 'flask'. But Flask is installed, and I'm running that in my virtual environment from the same directory as app.py. Why won't it run when I try it that way? Is there any advantage to using flask run rather than python app.py or vice versa?
One of the things I want to do is put the config & setup code inside an app factory. However, when I run with flask run, create_app doesn't run. What's going on there? I can make it run by uncommenting out the last 2 lines & looking for app instead of __main__, but shouldn't it run automatically?
Is there any advantage to adding a root-level __init__.py file? I tried briefly, but then none of the imports at the top of app.py worked. I kept getting a bunch of "No module named extensions", etc. errors. I can fix those by prefacing the names with dots, (e.g., from .extensions import db, mail), but what do I gain by doing that?
Thank you!
If you have a virtual env and you are getting the error ModuleNotFoundError: No module named 'flask', then you have to activate the virtual environment before you can run python app.py
If you're going to use create_app(), then the rest of your code should go under it i.e. app = Flask(__name__) and all of the app variable initializations and your route should go under it. As the name 'create app' says, you are creating the app

the module is not recognized in python (flask)

learning flask and new to web dev here ,
made the directories as below .
in folder named website and in a subfoder named templates make a file init_.py and outside the website folder ,main.py is there
code in init.py
from flask import Flask
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY']='madkrish'
return app
code in main.py
from website import create_app
app = create_app()
if __name__== '__main__':
app.run(debug=True)
When i run the main function the following errors comes:
No Module named 'website'
given above
Can someone please correct me where i am wrong i need to go further in the tutorial to the next step.
From your folder structure, you need to import from templates, so:
from templates import create_app
It should works.
VSCode will still marks it as error, you need to configure it to inlcude your templates folder in the Python Path

Where does Flask look to find config files when using flask.config.from_object()?

I've been trying to solve this for a couple days now. I'm running flask using the application setup as described in the tutorial. Below is are the packages installed in the virtual environment.
pip3 freeze
click==7.1.2 Flask==1.1.2 itsdangerous==1.1.0 Jinja2==2.11.2
MarkupSafe==1.1.1 pkg-resources==0.0.0 python-dotenv==0.15.0
Werkzeug==1.0.1
I have the following in a .env file:
FLASK_APP=myapp
just so I can do flask run. My directory structure looks like:
This is all contained within a directory called 'proj'
init.py
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('conf.DevConfig')
app.config.from_mapping(DATABASE=os.path.join(app.instance_path, 'tester.sqlite'))
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
#app.route('/hello')
def hello():
return 'Hello, World!'
return app
in proj I run flask run and get the following:
werkzeug.utils.ImportStringError: import_string() failed for 'conf.DevConfig'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Debugged import:
- 'conf' not found.
Original exception:
ModuleNotFoundError: No module named 'conf'
Notice that there is a conf.py in proj/instance/
conf.py contains
class Config(object):
DATABASE = 'tester.sqlite'
class DevConfig(Config):
DEBUG = True
class ProdConfig(Config):
DEBUG = False
Oddly enough, if I put conf.py in proj/ then the application loads just fine. I could have swore I read that Flask will search proj/instance by default for files. Why does it find it when I move it one level back from instance. For that matter can .env files be stored in instance and will flask auto find them? To me it seems like instance_relative_config=True isn't doing what it should be doing. What effect does calling flask run have if it is run in proj/ vs proj/myapp
you can consider this as (Not 100% sure), when you do flask run then create_app function is called and runned.
it is simply as adding a run_app.py file in proj outside of app which import create_app function as as run it
so run_app.py
from app import create_app
app = create_app()
if __name__=='__main__':
app.run()
this will run the server ( as you are doing now)
export FLASK_ENV=app or export FLASK_ENV=run_app.py are same
now as you have added config file in conf.py and it is working fine for you when that file is in proj folder not in instance folder. This is happening because in app/__init__.py file you have define the location of the config object as conf.DevConfig , so python is looking for this object in proj folder either.
since you have define the config object in instance/conf.py file, so python is not able to find it and giving you this error.
To solve This, you need to provide the location of the object in app.config.from_object('conf.DevConfig')
so you can do this in two way,
1st. provide full conf object path from the proj folder like
app.config.from_object('instance.conf.DevConfig')
2nd. import the instance in the app/__init__.py file and then provide the config object
eg. app/__init__.py
"""
import other packages
"""
from instance import conf
def create_app(test_config=None):
"""
app config thing here
"""
app.config.from_object(conf.DevConfig)
"""
config app more
"""
return app
Note in method one i am providng object as a string and in 2 as a class method
app.config.from_object() will search from where flask run is executed. In this case from the /proj directory
app.config.from_pyfile() will search at least in instance when instance_relative_config is set to true
As mentioned by sahasrara62: the devConfig class can be found in conf.py by using 'instance.conf.DevConfig'
I didn't notice any evidence that flask run add a run_app.py file and executes it, but it does seem that flask run starts off in the directory it is run from

Getting Error in VS Code while running Flask App

Trying to run the flask code in Vscode (mac Os x 10.14.15) but getting an error.
First I tried running:
python3 -m flask run
But, it showed
"Could locate a Flask application. You didnt provide Flask_App variable or wsgi.py or app.py was not found in the current directory.
I then ran the following command:
export Flask_app = app.py
(though I didnt need to export the variable since my file name is already app.py)
flask run
Could not import 'app'
Please note that I have verified that Flask version 1.0.3 is installed
Here is the code I'm trying to execute:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "Hello, Flask!"
Python script should have been created in env/bin. Program ran successfully after moving .py file in the bin folder.

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

Categories