0

I have the following routeing function in Flask but as I build my application it gets too messy with too many links.

What should I do if I want to separate or group the routers in a separate file?

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')


@app.route('/mylink', methods=['GET'])
def get_mylink():
    return render_template('mylink.html')

Or is it possible to packagesize the routers? For example,

import myrouter
myrouter.Run()

1 Answers1

1

When my app was getting unwieldy, I split up the routes and functions into different files, but not quite exactly like you are suggesting/asking about.

If your app follows the typical package structure and has, for example, an index and blog page:

/app
  /templates
    /blog.html
    /index.html
  /__init__.py
  /models.py
  /views.py

then you could consider turning the views.py file into a directory called views and create a .py file for each set of related routes within that directory. For example:

/app
  /templates
    /blog.html
    /index.html
  /views
    /blog.py
    /main.py
  /__init__.py
  /models.py

You just put each set of @app.route() decorators and corresponding function into the appropriate file. So for the home page you could put this and any other general routes (like login/logout)

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

into main.py in the views directory. You would need to import these in the app/__init__.py with from app.views import main, blog. And don't forget to include a blank __init__.py file in the views directory.

Spencer
  • 26
  • 3