14

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.

ensnare
  • 40,069
  • 64
  • 158
  • 224
  • 1
    Related (with answer): http://stackoverflow.com/questions/9395587/how-to-organize-a-relatively-large-flask-application – ccoakley Mar 08 '12 at 15:55

4 Answers4

14
  • 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.
Jarus
  • 1,748
  • 2
  • 13
  • 22
11

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.

Charles Roper
  • 20,125
  • 20
  • 71
  • 101
  • Hi, What if I want to do this with multiple models? I can't find much of anything that has modelS, just a single model.py file. What if I have dogs, cats, and cars and I want three models? – johnny Jan 29 '15 at 22:11
9

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.

jd.
  • 10,678
  • 3
  • 46
  • 55
0

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')
mkspeter3
  • 51
  • 2
  • 7