Reputation: 2911
I have a very small Flask app that is laid out as follows:
tinker/
main.py
/my_package
init.py
views.py
When I do tinker>python main.py everything runs fine. Here are the contents of each file:
main.py:
from my_package import app
app.run()
my_package/init.py:
from flask import Flask
app = Flask(__name__)
from my_package import views
my_package/views.py:
from my_package import app
@app.route('/')
def home():
return 'Ola!!!!!'
While all the above code runs fine when I try to modify it slightly by using a a create_app() code pattern, as in the below, views.py throws the following exception: "ImportError: cannot import name 'app' from 'my_package' " Is there a way to fix the problem without using Blueprints?
main.py:
from my_package import create_app
app = create_app()
app.run()
my_package/init.py:
from flask import Flask
def create_app():
app = Flask(__name__)
from my_package import views
return app
my_package/views.py:
from my_package import app
@app.route('/')
def home():
return 'Ola!!!!!'
Upvotes: 1
Views: 830
Reputation: 7945
You import the views within application context, then in the views you can use current_app.
in mypackage/__init__.py
:
def create_app():
app = Flask(__name__)
with app.app_context():
from . import views
in mypackage/views.py
:
from flask import current_app
@current_app.route('/')
def index():
return 'hello, world!'
Upvotes: 1
Reputation: 99
init.py needs to be renamed to __init__.py
Move app = Flask(__name__)
outside of the create_app
method
Change to from . import app
in views.py
Upvotes: -1