How to split flash application into multiple py files?

Currently, my flask application consists of a single test.py file with several routes and a specific main() route. Is there a way to create a test2.py file that contains routes that were not processed in test.py ?

 @app.route('/somepath') def somehandler(): # Handler code here 

I am worried that there test.py too many routes in test.py , and I would like to make python test.py run, which will also collect routes on test.py , as if it were part of the same file. What changes should I make in test.py and / or include in test2.py to make this work?

+94
python flask
Aug 16 '12 at 19:43
source share
4 answers

You can use the usual Python package structure to split your application into several modules, see Flask documents.

However

Flask uses the concept of drawings to create application components and support common patterns in an application or between applications.

You can create a subcomponent of your application 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) 

Drawings can also link specific resources: templates or static files. Please refer to flask documents for all details.

+110
Aug 16 2018-12-12T00:
source share

I would recommend a bottle empty on GitHub.

It provides an easy way to understand drawings , multiple views, and extensions .

+14
Aug 16 2018-12-12T00:
source share

Dividing the application into drawings is a great idea. However, if this is not enough, and if you want to split Blueprint itself into several py files, it is also possible using the usual Python module import system, and then iterate over all the routes that are imported from other files.

I created a Gist with the code for this:

https://gist.github.com/Jaza/61f879f577bc9d06029e

As far as I know, this is the only possible way to split Blueprint at the moment. It is not possible to create β€œsub-drawings” in Flask, although the problem is open with a lot of discussion about this:

https://github.com/mitsuhiko/flask/issues/593

Also, even if it were possible (and probably could have used some fragments from this stream of problems), sub-drawings may be too restrictive for your use case anyway - for example. if you do not want all routes in the submodule to have the same URL prefix.

+4
Feb 06 '15 at 4:08
source share

You can split like django. See below the skeleton

https://github.com/rohitchormale/cookiecutter-flask

0
Jan 25 '19 at 10:45
source share



All Articles