ensnare
ensnare

Reputation: 42033

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

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.

Upvotes: 14

Views: 13421

Answers (4)

mkspeter3
mkspeter3

Reputation: 71

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')

Upvotes: 0

Charles Roper
Charles Roper

Reputation: 20625

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.

Upvotes: 11

jd.
jd.

Reputation: 10948

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.

Upvotes: 9

Jarus
Jarus

Reputation: 1788

  • 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.

Upvotes: 14

Related Questions