Flask: each route in its own module file?

77 Views Asked by At

I have am developing a flask app that is both a regular website (serving HTML) and and a JSON API. It's structured like this (using blueprints for api and site)

Project
 |
 +-- views
 |  |  
 |  +-- api.py      <-- all routes for api
 |  +-- site.py     <-- all routes for regular site
 |
 +-- __init__.py
 +-- category.py    <-- main project dir contains shared object modules
 +-- helpers.py
 +-- product.py  
 ...

That works OK, except that as the project grows, having all the routes in the api.py and site.py modules causes them to grow a mile long.

I'd like to split out each route into its own module like this:

 Project
 |
 +-- views
 |  |  
 +  |-- api
 |  |  |
 |  |  +-- __init__.py 
 |  |  +-- cart.py        <-- each route has its own file
 |  |  +-- category.py
 |  |  +-- user.py 
 |  |  +-- ... 
 |  |  |
 +  |-- site 
 |  |  +-- __init__.py 
 |  |  +-- cart.py
 |  |  +-- category.py
 |  |  +-- user.py 
 |  |  +-- ... 
 |  |   
 +-- __init__.py
 +-- category.py 
 +-- helpers.py
 +-- product.py     
 ...

Or at least into modules that are grouped together like /user and all /user/* sub-routes would be put into ./views/api/user.py (for example).

How can this be accomplished? or, is there a better way to approach?

1

There are 1 best solutions below

0
tarponjargon On

Upon further research of blueprints, I realized that I was not really fully understanding and utilizing them. One of their main purposes is to chunk-ify route modules that are a mile long.