Reputation: 1062
I have an app structured like so:
name
-app.py
-__init__.py
-folder1
-views.py
-models.py
-__init__.py
The content of my app.py:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
if __name__ == '__main__':
app.run('0.0.0.0')
And init.py in the name folder is:
from app import app
How would I import this app into views.py? Currently, I'm using
from name import app
from models import Class1
app.add_url_rule('/', view_func=Class1.as_view('class1'))
, but then when I run the app it returns a 404 error.
Upvotes: 3
Views: 4366
Reputation: 6468
This is what I did to my apps:
In __init__.py
:
from .app import app
with app.app_context():
from .folder1 import models, views # noqa
In folder1/views.py
:
from flask import current_app as app
# then use `app` as usual
from .models import Class1
app.add_url_rule('/', view_func=Class1.as_view('class1'))
The "app_context()
" injects the current app
object into the current_app
proxy. Read this to understand the mechanism.
Also it is recommended to explicitly use relative imports (with the extra dots ".
").
Upvotes: 4