Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller classes in Flask

Tags:

python

flask

I'm digging into Flask with ASP.NET MVC / PHP MVC frameworks background. I'm not sure what is the prefered way of grouping actions (in the sense "function that process request").

In ASP.NET MVC actions are methods, controllers are classes. Controllers can be grouped into Areas. But flask application can be divided into modules and\or blueprints (looks like ASP.NET MVC Areas to me). Neither way uses classes, why?

Please check the great answer below, another option is Flask-Classy

like image 403
artvolk Avatar asked Mar 12 '14 15:03

artvolk


People also ask

What are controllers in Flask?

Flask supports all HTTP request methods. Controllers pass data into view templates and then render HTML using Jinja2.

What is __ init __ In Flask?

Files named __init__.py are used to mark directories on disk as Python package directories. So it really depends on your structure of projects. Ideally if you have a project with multiple folders, you might have to make them as python package directories.

Does Flask have MVC?

Flask follows MVC architecture whereas Django follows MVT architecture and both have their core differences. Flask Project is a single application where you can add countless views and models.

Can Flask handle multiple users?

As of Flask 1.0, flask server is multi-threaded by default. Each new request is handled in a new thread. This is a simple Flask application using default settings.


1 Answers

Just my opinion.

At first in most cases you do not need classes. I can't found cases where I really need classes to just connecting dispatchers to endpoints (I do not told about complex cases where you will use decorators or Pluggable Views). Do you have many instances of your controllers in ASP.MVC and etc? One? What about inheritance? I hope you understand my logic. You also can find interesting topics with stop writing classes keywords.

At second in python module with functions really very similar to class (singleton) and methods.

At third it just less nested.

For grouping actions I try split controllers (views with flask notation, see https://stackoverflow.com/a/20999302/880326) by logic, but you can have more important criterias for this. Easy example:

views/
    __init__.py
    about.py
    home.py
    products.py
    user/
        __init__.py
        dashboard.py
        product_1.py
        product_2.py
        product_3.py
        settings.py
like image 126
tbicr Avatar answered Oct 06 '22 20:10

tbicr