I have a relatively simple web application that is written in Python using the Flask microframework. I've really enjoyed Flask's ease of use, however, as the app has grown larger it has started to become unwieldy having all of my actions (and utility functions) in a single file. My views.py is about 700 lines of code and I'd really like to break things out into more discrete units. How should I restructure my code?
There are multiple ways to structure your application:
- The easiest is just to stick to the functions and move them to different files. For as long as you make sure they are imported when the application starts that's perfectly okay.
- Use Blueprints to assign the views to “categories”. For instance backend, auth, profile, etc. Blueprints have the advantage that they can in theory be attached to multiple applications and are also a great way to implement application factories.
- Use the underlying Werkzeug URL map and register functions on there on a central URL map.
For all these topics there are entries in the pattern section of the Flask documentation.