When creating a web application using Flask, which is a web framework of python, the number of lines in the Flask file tends to increase, so I considered file division. It seems that file splitting using Brueprint is common in Flask, and this time I used Blueprint to split the file.
├── main.py
├── COMP_A
│ └── func_A.py
├── COMP_B
│ └── func_B.py
└── templates
├── COMP_A
│ ├── index_A_1.html
│ └── index_A_2.html
└── COMP_B
├── index_B_1.html
└── index_B_2.html
The main program is main.py. In addition, it is assumed that there are components A and B. Func_A.py and func_B.py in each component are files that use Flask respectively.
In flask, the html file is stored under the template, but this time, a directory for each component was prepared under the template and the html file was stored.
func_A.py
from flask import render_template
from flask import Blueprint
bpa = Blueprint('bpa', __name__, url_prefix='/A')
@bpa.route('/a1')
def app_a1():
return render_template('COMP_A/index_A_1.html')
#return "hello A a1"
@bpa.route('/a2')
def app_a2():
return render_template('COMP_A/index_A_2.html')
#return "hello A a2"
func_B.py
from flask import render_template
from flask import Blueprint
bpb = Blueprint('bpb', __name__, url_prefix='/B')
@bpb.route('/b1')
def app_b1():
return render_template('COMP_B/index_B_1.html')
#return "hello B b1"
@bpb.route('/b2')
def app_b2():
return render_template('COMP_B/index_B_2.html')
#return "hello B b2"
main.py
from flask import Flask
app = Flask(__name__)
from COMP_A.func_A import bpa
from COMP_B.func_B import bpb
@app.route('/')
def index():
return 'Hello main'
app.register_blueprint(bpa)
app.register_blueprint(bpb)
if __name__ == '__main__':
app.debug = True
app.run(host='127.0.0.1',port=60000)
Originally, the function is registered for the app generated by Flask (name), but in the case of a function in another file, Brueprint is registered in the app using register_blueprint. At this time, don't forget to import another function Brueprint in advance.
Specify the following in the URL
127.0.0.1:60000/ #main.py index()
127.0.0.1:60000/A/a1 #func_A.py app_a1()
127.0.0.1:60000/A/a2 #func_A.py app_a2()
127.0.0.1:60000/B/b1 #func_B.py app_b1()
127.0.0.1:60000/B/b2 #func_B.py app_b2()
Note that the URL is a combination of Prefix when Brueprint is specified and the path when @ xxx.route is defined.
--File split using module There seems to be a way to split the file using flask.module. Consider next time.
return redirect(url_for('bpb.b2'))
Recommended Posts