Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

flask

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.

like image 439
ensnare Avatar asked Mar 08 '12 15:03

ensnare


People also ask

What are views in Flask?

A view function is the code you write to respond to requests to your application. Flask uses patterns to match the incoming request URL to the view that should handle it. The view returns data that Flask turns into an outgoing response.

Where does Flask look for static files?

Static files in Flask have a special route. All application URLs that begin with "/static", by convention, are served from a folder located at "/static" inside your application's root folder.

What is Send_from_directory in Flask?

send_from_directory (directory, filename, **options)[source] Send a file from a given directory with send_file() . This is a secure way to quickly expose static files from an upload folder or something similar.

How does the view function pass entries in Flask *?

In Flask, give an explanation for how does the view function will pass the entries? Answer: In Flask, the view feature will skip the entries as dicts to the show_entries. Html template and return the rendered one.


2 Answers

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.

like image 164
jd. Avatar answered Sep 23 '22 03:09

jd.


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

  • https://github.com/mitsuhiko/flask-website/tree/master/flask_website/views
  • https://bitbucket.org/imwilsonxu/fbone/src/a3f1439f6941/fbone/views

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

like image 28
Charles Roper Avatar answered Sep 25 '22 03:09

Charles Roper