My flask application currently consists of a single test.py
file with multiple routes and the main()
route defined. Is there some way I could create a test2.py
file that contains routes that were not handled in test.py
?
@app.route('/somepath')
def somehandler():
# Handler code here
I am concerned that there are too many routes in test.py
and would like to make it such that I can run python test.py
, which will also pick up the routes on test.py
as if it were part of the same file. What changes to I have to make in test.py
and/or include in test2.py
to get this to work?
You can use the usual Python package structure to divide your App into multiple modules, see the Flask docs.
However,
Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.
You can create a sub-component of your app as a Blueprint in a separate file:
simple_page = Blueprint('simple_page', __name__, template_folder='templates')
@simple_page.route('/<page>')
def show(page):
# stuff
And then use it in the main part:
from yourapplication.simple_page import simple_page
app = Flask(__name__)
app.register_blueprint(simple_page)
Blueprints can also bundle specific resources: templates or static files. Please refer to the Flask docs for all the details.