NameError: name 'app' is not defined with Flask
11,212
After do what Miguel suggest (use the Blueprint
) everything works, that's the final code, working:
_init.py_
...
def create_app(cfg=None):
app = Flask(__name__)
from api.views import api
app.register_blueprint(api)
return app
views.py
from flask import current_app, Blueprint, jsonify
api = Blueprint('api', __name__)
@api.route("/")
def index():
# We can use "current_app" to have access to our "app" object
return "Hello World!"
Author by
zot24
Updated on June 04, 2022Comments
-
zot24 about 2 years
I have the following structure in my project
\ myapp \ app __init__.py views.py run.py
And the following code:
run.py
from app import create_app if __name__ == '__main__': app = create_app() app.run(debug=True, host='0.0.0.0', port=5001)
views.py
@app.route("/") def index(): return "Hello World!"
_init_.py
from flask import Flask def create_app(): app = Flask(__name__) from app import views return app
I'm trying to use the
factory design pattern
to create myapp
objects with differentconfig
files each time, and with a subdomain dispatcher be able to create and route different objects depending on thesubdomain
on the user request.I'm following the Flask documentation where they talk about, all of this:
But I couldn't make it work, it seems that with my actual project
structure
there are no way to pass throw theapp
object to myviews.py
and it throw andNameError
NameError: name 'app' is not defined