In Flask, why are all the views shown in a single file?

Question:

Is there a way to split them up (view per file) or is this not recommendable? I’m working on a rather large project and will have a lot of views. Thanks.

Asked By: ensnare

||

Answers:

You can break down views in various ways. Here are a couple of examples:

And here’s another neat way of organizing your app: Flask-Classy. Classy indeed.

Answered By: Charles Roper
  • You could put the views into blueprints which create normally a very nice and clear structure in a flask application.
  • There is also a nice feature called Pluggable Views to create views from classes which is very helpful by a REST API.
Answered By: Jarus

Nothing prevents you from having your views split in multiple files. In fact, only the smallest of applications should consist of a single file.

Here’s how you would write a view in a dedicated file:

from flask import current_app

@current_app.route('/myview')
def myview():
    pass

Just make sure the module is imported at some point.

Of course, as the other answers suggest, there are techniques for structuring your application that promote ease of development and maintenance. Using blueprints is one of them.

Answered By: jd.

This can be accomplished by using Centralized URL Map

app.py

import views
from flask import Flask

app = Flask(__name__)

app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

views.py

from flask import render_template

def index():
    return render_template('index.html')

def other():
    return render_template('other.html')
Answered By: mkspeter3
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.