I am a beginner with Flask and I have created a project with an MVC structure
- CODE :
.
├── app
│. │── main.py
│ ├── controllers
│ │ ├── dbscan.py
│ │ ├── home.py
│ │ └── kmeans.py
│ ├── models
│ │ ├── dbscan.py
│ │ └── kmeans.py
│ ├── static
│ │ └── XXXX
│ └── views
│ └── XXXX
└── main.py
File main.py
from flask import Flask
app = Flask(
__name__,
template_folder='app/views',
static_folder='app/static'
)
if __name__ == "__main__":
app.run(debug=True)
File home.py
from flask import render_template
@app.route("/")
def home():
return render_template('home.html')
- ISSUE :
I already understood the problem but I don't know how to fix it...
There is no link between the controllers
files and the main.py
So, how I can link all routes present in controllers
folder and main.py
?
- UPDATE :
home.py
from flask import Blueprint, render_template
home_hdl = Blueprint('home_hdl', __name__, template_folder='views')
@home_hdl.route("/")
def home():
return render_template('home.html')
main.py
from flask import Flask
from app.controllers.home import home_hdl
app = Flask(
__name__,
template_folder='app/views',
static_folder='app/static'
)
app.register_blueprint(home_hdl)
if __name__ == "__main__":
app.run(debug=True)
Folders
.
├── app
│ ├── controllers
│ │ ├── __init__.py
│ │ ├── dbscan.py
│ │ ├── home.py
│ │ └── kmeans.py
│ ├── main.py
│ ├── models
│ │ └── XXXX
│ ├── static
│ │ └── XXXX
│ └── views
│ └── XXXX
└── XXXX
CodePudding user response:
Try this
Define a handler in each of the files you have under the controllers folder (the ones that will handle routing).
E.g. for the
dbscan.py
, you could have
from flask import Blueprint
dbscan_handlers = Blueprint('dbscan_handlers', __name__, template_folder='views')
# Your routes (in the dbscan.py file) will then be something like this
@dbscan_handlers.route('/xyz/'):
.....
@dbscan_handlers.route('/def/'):
....
- Then you register the handler in
main.py
from controllers.dbscan import dbscan_handlers
app.register_blueprint(dbscan_handlers)
Note that to do
from controllers.abc import xyz
, you need to have an__init.py__
file in controllers. The file can be empty.When someone accesses your app, it will go to main.py and if the route is of the pattern
/xyz/
, it will be handled by dbscan.py file