Search code examples
pythonclassdecoratorflasktornado

Why use classes vs decorators in Python Flask?


In Flask, you can use classes and decorators for routes. What would be the advantage of each use case?

I was thinking decorators for static pages and classes for more dynamic pages. If I was to combine tornado/gunicorn with flask, which is the better method.

I plan on using async methods, using this as a example as starting point: using Flask and Tornado together?

This post states it may framework dependent, but in flask we can use both.
Decorators vs. classes in python web development


Solution

  • These are my personal rules of the thumb.

    1. If I have to port from an existing application, I use the convention that is used in the source application. Having two possible routing styles is a big advantage.
    2. If the application uses different URLs for the same code, I create an explicit mapping between URLs and handler classes.
    3. If the number of URLs and classes used in the application is small, I will use decorators.
    4. If the application is complex, with complex URLs, I create an a mapping between URLs and handler classes.