Issue
I'm trying myself in web dev using Flask. First of all I decided to undtersand how to correctly organize directories in my app. So i used blueprints and got this:
/TestProj
├── config.py
├── __init__.py
└── /test_app
├── __init__.py
├── views.py
├── /static
└── /templates
Content of /TestProj/__init__.py
:
from flask import Flask
from .test_app import test_app
def create_app(test_config = None):
app = Flask(__name__)
app.register_blueprint(test_app, subdomain='test')
return app
Content of /test_app/__init__.py
:
from flask import Blueprint
test_app = Blueprint('test', __name__,
template_folder='templates', static_folder='static')
from . import views
Content of /test_app/views.py
:
from random import randint
from . import test_app
from flask import render_template
@test_app.route('/')
def index():
return('!!!!')
@test_app.route('/')
def getRandom(random):
return render_template('/test_app.html')
So, thats my questions:
I found that i can't start my app with
flask run
cause ofCould not locate a flask application
. Why is this happening? I thought that 'root'__init__.py
is like connecting link for all of apps in project and callingflask run
should lead to execute__init__.py
and PROFIT.Is this architecture corrent? I'll add more apps with same organize like test_app2 etc.
Which the best way to route index
('/')
page in this case? I wouldn't want to implement that in one of apps.Is it correct to create something like root app?
Note. If it matters, I'm using ubuntu 23.10, VSCode, Flask 3.0.0, Python 3.12.1 + venv
Solution
Creating a root app or a main blueprint is a valid approach, you can take a look at this tutorial to see how the splitting of blueprints can be handled for larger apps.
You can not start your app with flask run because you probably have not exposed the app ans an environment variable yet. To solve this create a .flaskenv
file at the same level you create your application instance.
Looking at your first code you a create_app function which is a good approach. Now you need to call this function somewhere to instantiate an app instance. Assuming you have not done this yet create for example TestProj.py
at your root directory so that your folder structure looks like this:
.flaskEnv
TestProj.py
/TestProj
├── config.py
├── __init__.py
└── /test_app
├── __init__.py
├── views.py
├── /static
└── /templates
Now inside TestProj.py
you create your app:
From TestProj import create_app
app = create_app(<your config>)
And now in .flaskenv
you can expose the app as an environment variable so that it can be found by flask run:
FLASK_APP=TestProj.py
FLASK_DEBUG=1
Now the flask run
command will start your app in debug mode
Answered By - Lenntror
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.