Reputation: 10482
I am starting a flask
project, and in my code I have
from flask import Flask, render_template, abort
app = Flask(__name__)
Now what exactly is app
?
I am following this guide and I am particularly confused about the structure because he has chosen to have directory named app/
and is his app/__init__.py
he has
from flask import Flask
app = Flask(__name__)
from app import views
and in his app/views.py
he has
from app import app
What the hell is it with all these app
's?!
Upvotes: 39
Views: 29557
Reputation: 23479
The author made his code needlessly confusing by choosing a package name that is the same as Flask's usual application object instance name. This is the one you'll be most interested in:
app = Flask(__name__)
Here is the documentation on the Flask application object:
http://flask.pocoo.org/docs/api/#application-object
To avoid confusion, I recommend using the official Flask documentation instead of that guide.
Upvotes: 17
Reputation: 33309
I think the main confusion is in the line:
from app import app
You have a python package (a folder with __init__.py
file) named "app". From this folder, you are now importing the variable "app" that you defined below in __init__.py
file:
app = Flask(__name__)
Rename the folder from app to say "myproject". Then you will call
from myproject import app
Also, you will import views as
from myproject import views
Upvotes: 41
Reputation: 34282
That's a bit confusing indeed, due to the poor names choice.
app = Flask(__name__)
: here app
is a WSGI application, it implements the corresponding interface and also supports whatever Flask has to offer us on top of that.from app import app
: imports exactly that app
object from the package app
.from app import view
: For what heck he's importing views
there, is a bit of a mystery, I suppose he wants to make sure that the view bindings are executed. (I'd rather do that in run.py
). In any case, that's a kind of importing loop between two modules which is at least confusing as well.Upvotes: 6